@mulmoclaude/core 4.3.0 → 4.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (33) hide show
  1. package/assets/helps/custom-view-remote.md +28 -11
  2. package/assets/helps/error-recovery.md +20 -3
  3. package/dist/{graph-BZJxiv1E.cjs → graph-CURotEkH.cjs} +88 -37
  4. package/dist/graph-CURotEkH.cjs.map +1 -0
  5. package/dist/{graph-Ce7xsDTt.js → graph-DBxSOx3v.js} +77 -38
  6. package/dist/graph-DBxSOx3v.js.map +1 -0
  7. package/dist/scheduler/index.cjs +116 -63
  8. package/dist/scheduler/index.cjs.map +1 -1
  9. package/dist/scheduler/index.js +117 -64
  10. package/dist/scheduler/index.js.map +1 -1
  11. package/dist/scheduler/schedule-window.d.ts +35 -0
  12. package/dist/scheduler/task-manager.d.ts +2 -8
  13. package/dist/{slug-CdN-pQX1.js → slug-BpjumQfe.js} +26 -5
  14. package/dist/{slug-CdN-pQX1.js.map → slug-BpjumQfe.js.map} +1 -1
  15. package/dist/{slug-DbwORN9z.cjs → slug-JxgB0ru9.cjs} +31 -4
  16. package/dist/{slug-DbwORN9z.cjs.map → slug-JxgB0ru9.cjs.map} +1 -1
  17. package/dist/wiki/graph.d.ts +0 -5
  18. package/dist/wiki/index.cjs +5 -2
  19. package/dist/wiki/index.d.ts +3 -2
  20. package/dist/wiki/index.js +3 -3
  21. package/dist/wiki/lint.d.ts +8 -9
  22. package/dist/wiki/paths.cjs +1 -1
  23. package/dist/wiki/paths.js +1 -1
  24. package/dist/wiki/resolve.d.ts +24 -0
  25. package/dist/wiki/server/engine.d.ts +12 -4
  26. package/dist/wiki/server/index.cjs +46 -34
  27. package/dist/wiki/server/index.cjs.map +1 -1
  28. package/dist/wiki/server/index.js +46 -34
  29. package/dist/wiki/server/index.js.map +1 -1
  30. package/dist/wiki/slug.d.ts +14 -3
  31. package/package.json +1 -1
  32. package/dist/graph-BZJxiv1E.cjs.map +0 -1
  33. package/dist/graph-Ce7xsDTt.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graph-DBxSOx3v.js","names":[],"sources":["../src/wiki/link.ts","../src/wiki/resolve.ts","../src/wiki/index-parse.ts","../src/wiki/lint.ts","../src/wiki/graph.ts"],"sourcesContent":["// Pure helpers for `[[wiki-link]]` syntax. Used by the lint\n// (`server/api/routes/wiki.ts`), the page resolver, and the\n// frontend renderer (`src/plugins/wiki/helpers.ts`) — before this\n// module the three sites each had their own implementation and\n// none of them handled the `[[target|display]]` form, producing\n// false-positive \"broken link\" warnings on slug-aliased links\n// (issue #1297).\n//\n// All functions are pure string operations; safe to import from\n// browser bundles. No `node:*` imports anywhere in this file.\n\n/** Inline `[[...]]` link pattern. The capture group is the raw\n * text between the brackets — the caller is expected to feed it\n * through `parseWikiLink` to split off any `|display` suffix.\n *\n * Body length is capped at 200 chars to keep the regex linear:\n * catastrophic backtracking isn't possible (no nested\n * alternation), but a malicious page with thousands of\n * unmatched `[[` could still pin the CPU. 200 is well above the\n * longest legitimate title we've seen and matches the cap the\n * server-side `WIKI_LINK_PATTERN` constant has carried since the\n * original implementation in #951.\n *\n * Shared with the renderer's hand-rolled scanner so the two can't\n * drift: the renderer must reject the same newline-bearing and\n * over-length bodies, or a link would render clickable while the\n * graph / backlinks / lint (which use this pattern) never see it. */\nexport const WIKI_LINK_MAX_LEN = 200;\nexport const WIKI_LINK_PATTERN = new RegExp(`\\\\[\\\\[([^\\\\][\\\\r\\\\n]{1,${WIKI_LINK_MAX_LEN}})\\\\]\\\\]`, \"g\");\n\n/** The structural shape of an inline `[[target|display]]` link.\n * `target` is what the resolver / lint compares against page\n * slugs; `display` is what the renderer shows to the user.\n * When the user writes `[[foo]]` (no pipe), both fields hold\n * `foo`. */\nexport interface WikiLink {\n target: string;\n display: string;\n}\n\n/** Split the raw text inside `[[...]]` into target + display.\n *\n * - `[[foo|Bar Baz]]` → `{ target: \"foo\", display: \"Bar Baz\" }`\n * - `[[foo]]` → `{ target: \"foo\", display: \"foo\" }`\n * - `[[|empty target]]` → `{ target: \"\", display: \"empty target\" }`\n * (caller decides whether an empty target is meaningful;\n * typically lint flags it, renderer shows the display text raw)\n * - `[[foo|]]` → `{ target: \"foo\", display: \"\" }`\n * (same — caller decides)\n *\n * Whitespace around the pipe is preserved on the display side\n * (so the user can write `[[foo| ある記事 ]]` and get the\n * spacing intentionally) but TRIMMED on the target side, since\n * a slug-comparable target with leading/trailing whitespace is\n * always a typo.\n *\n * Only the FIRST pipe splits. `[[a|b|c]]` becomes\n * `{ target: \"a\", display: \"b|c\" }` so display strings can\n * legitimately contain a literal `|`. */\nexport function parseWikiLink(inner: string): WikiLink {\n const pipeIdx = inner.indexOf(\"|\");\n if (pipeIdx === -1) {\n return { target: inner, display: inner };\n }\n const target = inner.slice(0, pipeIdx).trim();\n const display = inner.slice(pipeIdx + 1);\n return { target, display };\n}\n","// The one rule for \"does this `[[link]]` target name an existing page?\".\n// Shared by the page resolver, the lint, and the graph so the three\n// cannot disagree on which files a target can reach.\n//\n// Pure string + lookup work; safe to import from browser bundles.\n\nimport type { WikiPageEntry } from \"./index-parse.js\";\nimport { wikiSlugify } from \"./slug.js\";\n\n/** Anything that can answer \"do you hold this slug?\" — the page index\n * (`Map<slug, filename>`) and the lint's `Set<slug>` both qualify. */\nexport interface SlugLookup {\n has: (slug: string) => boolean;\n}\n\n/** Match a raw link target against known page slugs, returning the\n * matched slug or null.\n *\n * Literal first: page slugs ARE filename stems, so a non-ASCII page\n * only ever matches its own untouched name — `wikiSlugify` strips\n * every non-ASCII character and would reduce `不耕起栽培-カバークロップ4年計画`\n * to `-4` (#2940). The slugified form still runs second so\n * `[[Sakura Internet]]` keeps resolving to `sakura-internet.md`. */\nexport function matchWikiSlug(target: string, known: SlugLookup): string | null {\n const literal = target.trim();\n if (literal.length === 0) return null;\n if (known.has(literal)) return literal;\n const slug = wikiSlugify(literal);\n if (slug.length > 0 && known.has(slug)) return slug;\n return null;\n}\n\n/** index.md title → slug, first entry wins. The fallback for links\n * written as the display title rather than the page's own name. */\nexport function slugByIndexTitle(entries: readonly WikiPageEntry[]): Map<string, string> {\n const map = new Map<string, string>();\n entries.forEach((entry) => {\n if (entry.title.length > 0 && !map.has(entry.title)) map.set(entry.title, entry.slug);\n });\n return map;\n}\n\n/** Resolve a raw `[[link]]` target to an existing page slug, or null:\n * known slug first, then an index entry's title. Every consumer that\n * judges whether a link points at a real page — the graph and the\n * lint — shares this, so a link cannot be an edge in one and a broken\n * link in the other. */\nexport function resolveLinkTarget(target: string, fileSlugs: SlugLookup, slugByTitle: ReadonlyMap<string, string>): string | null {\n const matched = matchWikiSlug(target, fileSlugs);\n if (matched !== null) return matched;\n const byTitle = slugByTitle.get(target.trim());\n return byTitle !== undefined && fileSlugs.has(byTitle) ? byTitle : null;\n}\n","// Pure parsers for `data/wiki/index.md` content. Used by:\n// - server/api/routes/wiki.ts — page resolver + lint\n// - frontend lint preview (future) — same parser, no fork\n//\n// All exports here are pure string ops; no `node:*` imports allowed.\n// If a future caller needs to walk the filesystem, that wrapper goes\n// under `@mulmoclaude/core/wiki/server` (today only `server/paths.ts`\n// touches `node:path`; nothing here touches disk).\n\nimport { parseWikiLink } from \"./link.js\";\nimport { wikiPageStem, wikiSlugify } from \"./slug.js\";\n\nexport interface WikiPageEntry {\n title: string;\n slug: string;\n description: string;\n tags: string[];\n}\n\n// ── Patterns ──────────────────────────────────────────────────\n// Bullet patterns live here (not server/utils/regex.ts) because the\n// index parser is the only consumer and the regexes are part of the\n// public surface that callers may want to reason about in tests.\n// Linear in line length: every `[^x]+` runs over a fixed exclusion\n// set with a hard delimiter; the optional summary group's `(.*)` is\n// a single greedy run with no nested overlap.\n\n// eslint-disable-next-line security/detect-unsafe-regex -- bullet-link parser; bounded captures with hard delimiters\nexport const BULLET_LINK_PATTERN = /^[-*]\\s+\\[([^\\]]+)\\]\\(([^)]*)\\)(?:\\s*[—–-]\\s*(.*))?/;\n// eslint-disable-next-line security/detect-unsafe-regex -- same shape as BULLET_LINK_PATTERN\nexport const BULLET_WIKI_LINK_PATTERN = /^[-*]\\s+\\[\\[([^\\]]+)\\]\\](?:\\s*[—–-]\\s*(.*))?/;\n\nconst TABLE_SEPARATOR_PATTERN = /^\\|[\\s|:-]+\\|$/;\n\n// Unicode-aware tag body: any letter or number in any script (so\n// Japanese / Chinese / Korean tags like `#クラウド` or `#可視化` work),\n// plus `-` and `_` as internal joiners. First char is a letter or\n// number only — no leading punctuation.\nconst HASHTAG_PATTERN = /(?:^|\\s)#([\\p{L}\\p{N}][\\p{L}\\p{N}_-]*)/gu;\n\n// ── Tag extraction ────────────────────────────────────────────\n\n/** Extract `#tag` tokens from a bullet description, returning the\n * stripped description and a sorted, deduped, lowercased tag list.\n * Only matches at word boundaries so mid-word `#` (e.g. anchor\n * URLs) is left alone. */\nexport function extractHashTags(text: string): { description: string; tags: string[] } {\n HASHTAG_PATTERN.lastIndex = 0;\n const tags = [...text.matchAll(HASHTAG_PATTERN)].flatMap(([, tag]) => (tag ? [tag.toLowerCase()] : []));\n const description = text.replace(HASHTAG_PATTERN, \"\").replace(/\\s+/g, \" \").trim();\n const deduped = [...new Set(tags)].sort();\n return { description, tags: deduped };\n}\n\n/** Split a table Tags cell — tolerates comma, whitespace, or `#`\n * prefixes. Empty cell yields an empty list. */\nexport function parseTagsCell(cell: string): string[] {\n const tokens = cell\n .split(/[,\\s]+/)\n .map((token) => token.trim().replace(/^#/, \"\").toLowerCase())\n .filter((token) => token.length > 0);\n return [...new Set(tokens)].sort();\n}\n\n// ── Table parser ──────────────────────────────────────────────\n\n/** Map header cell names → column indices, case- and whitespace-\n * tolerant. Used by the row parser to locate the Tags column (and\n * any other named column) without assuming a fixed position, so\n * older 3- and 4-column tables keep working. */\nexport function buildTableColumnMap(headerRow: string): Map<string, number> {\n const cells = headerRow\n .split(\"|\")\n .slice(1, -1)\n // Mirror parseTableRow's cell-normalising: strip the surrounding\n // backticks that commonly wrap cell values in wiki tables.\n // Without this, a `| \\`tags\\` |` header maps to the key \"`tags`\"\n // and the subsequent `columnMap.get(\"tags\")` lookup silently\n // misses the column, falling back to `tags: []`.\n .map((cell) => cell.trim().replace(/^`|`$/g, \"\").toLowerCase());\n const map = new Map<string, number>();\n cells.forEach((cell, i) => {\n if (cell) map.set(cell, i);\n });\n return map;\n}\n\ninterface TableColumnIndices {\n slug: number;\n title: number;\n summary: number;\n /** Undefined when the table has no `tags` column — caller skips\n * the tags lookup entirely and the row gets `tags: []`. */\n tags: number | undefined;\n}\n\n/** Resolve the per-column indices the row parser needs. Falls back\n * to positional defaults (0/1/2) when the table has no header map.\n * \"summary\" is the canonical column name; \"description\" is accepted\n * as a legacy alias used by older fixtures. */\nfunction resolveTableColumnIndices(columnMap: Map<string, number> | null): TableColumnIndices {\n return {\n slug: columnMap?.get(\"slug\") ?? 0,\n title: columnMap?.get(\"title\") ?? 1,\n summary: columnMap?.get(\"summary\") ?? columnMap?.get(\"description\") ?? 2,\n tags: columnMap?.get(\"tags\"),\n };\n}\n\nfunction parseTableRow(trimmed: string, columnMap: Map<string, number> | null): WikiPageEntry | null {\n const cols = trimmed\n .split(\"|\")\n .slice(1, -1)\n .map((column) => column.trim().replace(/^`|`$/g, \"\"));\n if (cols.length < 2) return null;\n\n const idx = resolveTableColumnIndices(columnMap);\n const slug = cols[idx.slug] ?? \"\";\n const title = cols[idx.title] || slug;\n if (!slug || !title) return null;\n\n const description = cols[idx.summary] ?? \"\";\n const tags = idx.tags !== undefined ? parseTagsCell(cols[idx.tags] ?? \"\") : [];\n return { title, slug, description, tags };\n}\n\n// ── Bullet-row parsers ────────────────────────────────────────\n\n/** Extract the slug segment from a bullet link's href. Accepts the\n * canonical `pages/<slug>.md`, a bare `<slug>.md`, or just `<slug>`\n * — the three forms produced by different historical writers of\n * index.md. Returns \"\" for hrefs that don't look like a wiki page\n * reference (e.g. `https://example.com`) so the caller can fall\n * back to title-based slugification. */\nexport function extractSlugFromBulletHref(rawHref: string): string {\n const href = rawHref.trim();\n if (!href) return \"\";\n if (/^[a-z]+:\\/\\//i.test(href)) return \"\";\n const lastSegment = href.split(\"/\").pop() ?? href;\n return lastSegment.replace(/\\.md$/i, \"\");\n}\n\n/** Slug for an entry whose only identifier is human-written text.\n * A page file may be named in Japanese, and its slug IS that filename\n * stem — slugifying would index `-4` and leave the real file reported\n * as both missing and orphaned (#2944). `wikiPageStem` keeps the\n * hyphenated convention for ASCII and returns null for a name no file\n * could carry, where the old slug is still the best guess. */\nfunction entrySlugFor(name: string): string {\n return wikiPageStem(name) ?? wikiSlugify(name);\n}\n\nfunction parseBulletLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n const title = match[1]?.trim() ?? \"\";\n const href = match[2] ?? \"\";\n const raw = match[3]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n // Prefer the slug embedded in the href so non-ASCII titles keep\n // a navigable slug. Fall back to the title only when the href has\n // no recognisable slug (rare — usually means the author put an\n // external URL here).\n const slug = extractSlugFromBulletHref(href) || entrySlugFor(title);\n return { title, slug, description, tags };\n}\n\nfunction parseBulletWikiLinkRow(trimmed: string): WikiPageEntry | null {\n const match = BULLET_WIKI_LINK_PATTERN.exec(trimmed);\n if (!match) return null;\n // Split `[[target|display]]` so the bullet entry's slug derives\n // from the TARGET (which is already a slug-shaped identifier\n // when the author wrote the alias form) and the title shows\n // the DISPLAY half. Pre-#1297 the parser slugified the full\n // `target|display` body, which collapses `|` to \"\" and\n // produces a wrong slug — Codex review on PR #1312.\n const { target, display } = parseWikiLink(match[1] ?? \"\");\n const title = (display || target).trim();\n // No title fallback: an explicitly empty target (`- [[|display]]`) is\n // malformed, and borrowing the display half would let it name a real\n // page — silently accepting the typo instead of reporting it. An\n // empty slug reaches `findMissingFiles`, which says so (#2944).\n const slug = entrySlugFor(target);\n const raw = match[2]?.trim() ?? \"\";\n const { description, tags } = extractHashTags(raw);\n return { title, slug, description, tags };\n}\n\n// ── Top-level parser ──────────────────────────────────────────\n\n/** Parse entries from index.md. Supports three formats:\n * 1. Table: `| slug | Title | Summary | (Tags) |`\n * 2. Bullet link: `- [Title](pages/slug.md) — description`\n * 3. Wiki link: `- [[Title]] — description`\n *\n * Returns entries in source order. Any unrecognised line is\n * silently skipped — index.md is freeform markdown otherwise. */\nexport function parseIndexEntries(content: string): WikiPageEntry[] {\n const entries: WikiPageEntry[] = [];\n let inTable = false;\n let columnMap: Map<string, number> | null = null;\n\n for (const line of content.split(\"\\n\")) {\n const trimmed = line.trim();\n\n if (trimmed.startsWith(\"|\")) {\n if (TABLE_SEPARATOR_PATTERN.test(trimmed)) {\n inTable = true;\n continue;\n }\n if (!inTable) {\n // First `|`-line before the separator is the header. Capture\n // the column map so parseTableRow can locate the Tags\n // column (if any) by name rather than position.\n columnMap = buildTableColumnMap(trimmed);\n inTable = true;\n continue;\n }\n const entry = parseTableRow(trimmed, columnMap);\n if (entry) entries.push(entry);\n continue;\n }\n\n inTable = false;\n columnMap = null;\n\n const bullet = parseBulletLinkRow(trimmed) ?? parseBulletWikiLinkRow(trimmed);\n if (bullet) entries.push(bullet);\n }\n return entries;\n}\n","// Pure wiki lint rules.\n//\n// Each rule takes plain inputs (Sets, page-entry arrays, raw file\n// contents) so the whole pipeline can be unit-tested without\n// filesystem fixtures. The Express route at\n// `server/api/routes/wiki.ts` is a thin shell that reads the disk,\n// calls these rules, formats the result. A future frontend \"lint\n// preview before save\" would call the same functions over an\n// in-memory snapshot.\n\nimport type { WikiPageEntry } from \"./index-parse.js\";\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { resolveLinkTarget } from \"./resolve.js\";\nimport { wikiPageStem } from \"./slug.js\";\n\n/** Files on disk that aren't referenced by index.md. */\nexport function findOrphanPages(fileSlugs: ReadonlySet<string>, indexedSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const slug of fileSlugs) {\n if (!indexedSlugs.has(slug)) {\n issues.push(`- **Orphan page**: \\`${slug}.md\\` exists but is missing from index.md`);\n }\n }\n return issues;\n}\n\n/** Slugs referenced by index.md that have no corresponding file. */\nexport function findMissingFiles(pageEntries: readonly WikiPageEntry[], fileSlugs: ReadonlySet<string>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n if (entry.slug.length === 0) {\n issues.push(`- **Malformed entry**: index.md lists \\`${entry.title}\\` with no page name`);\n } else if (!fileSlugs.has(entry.slug)) {\n issues.push(`- **Missing file**: index.md references \\`${entry.slug}\\` but the file does not exist`);\n }\n }\n return issues;\n}\n\n/** One `[[…]]` body's diagnostic, or null when the link resolves.\n *\n * Critically: this routes through `parseWikiLink` so\n * `[[slug|display]]` is split correctly — the lint resolves the\n * TARGET, not the full bracket body. Pre-#1297 the lint\n * slugified the entire content (`slug|display`), which collapsed\n * to a slug that always missed and produced ~168 false-positive\n * \"broken link\" warnings. */\nfunction brokenLinkIssue(fileName: string, body: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string | null {\n const { target } = parseWikiLink(body);\n // Empty target is its own diagnostic — `[[|display]]` has nothing to\n // resolve and would otherwise be flagged identically to a real broken\n // link. Keep the original raw bracket body in the report so the user\n // can grep their pages for the malformed link. (`[[]]` never reaches\n // here: a zero-length body matches neither `WIKI_LINK_PATTERN` nor the\n // renderer's scanner, so it stays literal text everywhere.)\n if (target.trim().length === 0) return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → empty target`;\n if (resolveLinkTarget(target, fileSlugs, slugByTitle) !== null) return null;\n const stem = wikiPageStem(target);\n // A target the write guard would reject has no file to suggest —\n // saying `../secrets.md not found` invites creating what cannot\n // exist (CodeRabbit review).\n if (stem === null) return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → \\`${target.trim()}\\` cannot be a page filename`;\n return `- **Broken link** in \\`${fileName}\\`: [[${body}]] → \\`${stem}.md\\` not found`;\n}\n\n/** Walk a page's body for `[[…]]` links and flag any whose target\n * doesn't resolve to a file.\n *\n * `slugByTitle` (from `slugByIndexTitle`) is what lets a link written\n * as an index.md display title count as resolved — without it the\n * lint calls broken exactly the links the page resolver and the graph\n * follow happily. It defaults to empty so a caller linting an\n * in-memory snapshot with no index still works. */\nexport function findBrokenLinksInPage(\n fileName: string,\n content: string,\n fileSlugs: ReadonlySet<string>,\n slugByTitle: ReadonlyMap<string, string> = new Map(),\n): string[] {\n return [...content.matchAll(WIKI_LINK_PATTERN)]\n .map(([, body = \"\"]) => brokenLinkIssue(fileName, body, fileSlugs, slugByTitle))\n .filter((issue): issue is string => issue !== null);\n}\n\nfunction formatTagList(tags: readonly string[]): string {\n return `[${[...tags].sort().join(\", \")}]`;\n}\n\n/** Flag any slug whose index.md tags differ from the page's own\n * frontmatter `tags:` field. Comparison is set-based and order-\n * insensitive; both sides are lowercased at parse time. Slugs\n * missing from `frontmatterTagsBySlug` are ignored here — the\n * missing file itself is already reported by `findMissingFiles`. */\nexport function findTagDrift(pageEntries: readonly WikiPageEntry[], frontmatterTagsBySlug: ReadonlyMap<string, readonly string[]>): string[] {\n const issues: string[] = [];\n for (const entry of pageEntries) {\n // Lowercase on lookup — the caller keys the map with\n // lowercased slugs, so a `MyPage.md` filename still matches\n // an `entry.slug` of `mypage` produced by `wikiSlugify` on the\n // wiki-link parser path.\n const pageTags = frontmatterTagsBySlug.get(entry.slug.toLowerCase());\n if (pageTags === undefined) continue;\n const pageSet = new Set(pageTags);\n const indexSet = new Set(entry.tags);\n if (pageSet.size !== indexSet.size || [...pageSet].some((tag) => !indexSet.has(tag))) {\n issues.push(`- **Tag drift**: \\`${entry.slug}.md\\` frontmatter has ${formatTagList(pageTags)} but index.md has ${formatTagList(entry.tags)}`);\n }\n }\n return issues;\n}\n\n/** Render the final markdown report from the accumulated issues\n * list. Empty input yields the \"wiki is healthy\" sentinel so the\n * caller can write the same file every time without branching on\n * presence. */\nexport function formatLintReport(issues: readonly string[]): string {\n if (issues.length === 0) {\n return \"# Wiki Lint Report\\n\\n✓ No issues found. Wiki is healthy.\";\n }\n const noun = `issue${issues.length !== 1 ? \"s\" : \"\"}`;\n return `# Wiki Lint Report\\n\\n${issues.length} ${noun} found:\\n\\n${issues.join(\"\\n\")}`;\n}\n","// Pure builder for the wiki page→page link graph. Used by:\n// - server/api/routes/wiki.ts — the `graph` action endpoint\n// - src/plugins/wiki/View.vue — backlinks (\"linked references\") +\n// the Graph tab\n//\n// All functions are pure string / collection ops; no `node:*` imports,\n// so the frontend bundle can import them directly (same discipline as\n// the sibling `link.ts` / `lint.ts` / `index-parse.ts` modules).\n//\n// NOTE: this is page→page link structure, distinct from the\n// `server/workspace/wiki-backlinks/` module, which appends *session*\n// backlinks (a page → the chat that edited it, #109). Different concept\n// — do not conflate.\n\nimport { WIKI_LINK_PATTERN, parseWikiLink } from \"./link.js\";\nimport { resolveLinkTarget, slugByIndexTitle } from \"./resolve.js\";\nimport type { WikiPageEntry } from \"./index-parse.js\";\n\nexport interface WikiGraphNode {\n slug: string;\n title: string;\n}\n\nexport interface WikiGraphEdge {\n from: string;\n to: string;\n}\n\nexport interface WikiGraph {\n nodes: WikiGraphNode[];\n edges: WikiGraphEdge[];\n}\n\n/** One page's raw body plus its canonical (file-derived) slug. */\nexport interface WikiPageContent {\n slug: string;\n content: string;\n}\n\n/** Resolved, deduped outgoing slugs for one page body. Self-links and\n * links to non-existent pages are dropped (the latter are already a\n * lint \"broken link\", not a graph edge). */\nexport function pageOutgoingSlugs(fromSlug: string, content: string, fileSlugs: ReadonlySet<string>, slugByTitle: ReadonlyMap<string, string>): string[] {\n const out = new Set<string>();\n for (const [, body = \"\"] of content.matchAll(WIKI_LINK_PATTERN)) {\n const { target } = parseWikiLink(body);\n const resolved = resolveLinkTarget(target, fileSlugs, slugByTitle);\n if (resolved !== null && resolved !== fromSlug) out.add(resolved);\n }\n return [...out];\n}\n\nfunction buildTitleMaps(entries: readonly WikiPageEntry[]): { titleBySlug: Map<string, string>; slugByTitle: Map<string, string> } {\n const titleBySlug = new Map<string, string>();\n entries.forEach((entry) => {\n if (!titleBySlug.has(entry.slug)) titleBySlug.set(entry.slug, entry.title);\n });\n return { titleBySlug, slugByTitle: slugByIndexTitle(entries) };\n}\n\n/** Build the full page→page graph. Nodes are the existing page files\n * (titled from index.md, falling back to the slug for un-indexed\n * pages); edges are the resolved `[[links]]`, deduped per (from,to). */\nexport function buildWikiGraph(pages: readonly WikiPageContent[], entries: readonly WikiPageEntry[]): WikiGraph {\n const fileSlugs = new Set(pages.map((page) => page.slug));\n const { titleBySlug, slugByTitle } = buildTitleMaps(entries);\n const nodes: WikiGraphNode[] = pages.map((page) => ({ slug: page.slug, title: titleBySlug.get(page.slug) ?? page.slug }));\n const edges: WikiGraphEdge[] = [];\n const seen = new Set<string>();\n for (const page of pages) {\n for (const toSlug of pageOutgoingSlugs(page.slug, page.content, fileSlugs, slugByTitle)) {\n // Newline cannot appear in a wiki slug, so it is a safe pair key.\n const key = [page.slug, toSlug].join(\"\\n\");\n if (seen.has(key)) continue;\n seen.add(key);\n edges.push({ from: page.slug, to: toSlug });\n }\n }\n return { nodes, edges };\n}\n\n/** Pages that link TO `slug` (incoming edges), deduped, as nodes. */\nexport function incomingLinks(graph: WikiGraph, slug: string): WikiGraphNode[] {\n const nodeBySlug = new Map(graph.nodes.map((node) => [node.slug, node]));\n const result: WikiGraphNode[] = [];\n const seen = new Set<string>();\n for (const edge of graph.edges) {\n if (edge.to !== slug || seen.has(edge.from)) continue;\n seen.add(edge.from);\n const node = nodeBySlug.get(edge.from);\n if (node) result.push(node);\n }\n return result;\n}\n"],"mappings":";AA4BA,IAAa,oBAAoB,IAAI,OAAO,sCAAuD,GAAG;;;;;;;;;;;;;;;;;;;;AA+BtG,SAAgB,cAAc,OAAyB;CACrD,MAAM,UAAU,MAAM,QAAQ,GAAG;CACjC,IAAI,YAAY,IACd,OAAO;EAAE,QAAQ;EAAO,SAAS;CAAM;CAIzC,OAAO;EAAE,QAFM,MAAM,MAAM,GAAG,OAAO,CAAC,CAAC,KAE9B;EAAQ,SADD,MAA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IAAI,CAAC,CAAC;CACvE,MAAM,SAA0B,CAAC;CACjC,MAAM,uBAAO,IAAI,IAAY;CAC7B,KAAK,MAAM,QAAQ,MAAM,OAAO;EAC9B,IAAI,KAAK,OAAO,QAAQ,KAAK,IAAI,KAAK,IAAI,GAAG;EAC7C,KAAK,IAAI,KAAK,IAAI;EAClB,MAAM,OAAO,WAAW,IAAI,KAAK,IAAI;EACrC,IAAI,MAAM,OAAO,KAAK,IAAI;CAC5B;CACA,OAAO;AACT"}
@@ -6,11 +6,86 @@ let node_path = require("node:path");
6
6
  node_path = require_rolldown_runtime.__toESM(node_path, 1);
7
7
  let node_fs_promises = require("node:fs/promises");
8
8
  let _receptron_task_scheduler = require("@receptron/task-scheduler");
9
- //#region src/scheduler/task-manager.ts
9
+ //#region src/scheduler/schedule-window.ts
10
10
  var ONE_SECOND_MS$1 = 1e3;
11
- var ONE_MINUTE_MS = 60 * ONE_SECOND_MS$1;
12
- var ONE_HOUR_MS = 60 * ONE_MINUTE_MS;
13
- var DEFAULT_FIRING_STAGGER_MS = ONE_SECOND_MS$1;
11
+ var ONE_DAY_MS = 86400 * ONE_SECOND_MS$1;
12
+ /** An interval this engine can never turn into a window. Zero divides by zero
13
+ * inside the library's `Math.ceil(afterMs / intervalMs)`; a negative or
14
+ * non-finite one poisons the arithmetic with NaN, which compares false
15
+ * everywhere and so hides itself. */
16
+ function isUsableInterval(intervalMs) {
17
+ return Number.isFinite(intervalMs) && intervalMs > 0;
18
+ }
19
+ /** Milliseconds past UTC midnight for a daily `HH:MM`, or null when the string
20
+ * does not name a time of day. Out-of-range values are rejected, not clamped
21
+ * and not wrapped: `"24:00"` would otherwise land on the NEXT day's midnight
22
+ * and `"-1:00"` on an hour before it, so a typo that used to be inert would
23
+ * start firing — at 00:00 daily, or 61 times a day. */
24
+ function dailyOffsetMs(time) {
25
+ const offsetMs = (0, _receptron_task_scheduler.parseTimeToMs)(time);
26
+ return Number.isFinite(offsetMs) && offsetMs >= 0 && offsetMs < ONE_DAY_MS ? offsetMs : null;
27
+ }
28
+ /** Convert to the library's schedule shape. Milliseconds are divided, never
29
+ * rounded: rounding a sub-second interval to `intervalSec: 0` is what made
30
+ * `nextWindowAfter` answer NaN and `new Date(NaN).toISOString()` throw. */
31
+ function toLibrarySchedule(schedule) {
32
+ if (schedule.type === _receptron_task_scheduler.SCHEDULE_TYPES.interval) return {
33
+ type: _receptron_task_scheduler.SCHEDULE_TYPES.interval,
34
+ intervalSec: schedule.intervalMs / ONE_SECOND_MS$1
35
+ };
36
+ return {
37
+ type: _receptron_task_scheduler.SCHEDULE_TYPES.daily,
38
+ time: schedule.time
39
+ };
40
+ }
41
+ /** True when a scheduled window falls inside the tick ending at `nowMs`.
42
+ * Windows are anchored to the epoch, not to the current UTC day, so an
43
+ * interval longer than 24h keeps its real period. */
44
+ function isScheduleDueAt(schedule, nowMs, tickMs) {
45
+ if (unfireableScheduleReason(schedule) !== null) return false;
46
+ return (0, _receptron_task_scheduler.isDueAt)(toLibrarySchedule(schedule), nowMs, tickMs);
47
+ }
48
+ /** The furthest instant `Date` can represent. A window past it is finite
49
+ * arithmetic but not a date, and `toISOString()` answers that with a throw —
50
+ * which, inside the state writer, silently loses the whole run record. */
51
+ var MAX_DATE_MS = 864e13;
52
+ /** A window as an ISO timestamp, or null when the number is not a date. */
53
+ function windowToIso(windowMs) {
54
+ if (windowMs === null || !Number.isFinite(windowMs) || Math.abs(windowMs) > MAX_DATE_MS) return null;
55
+ return new Date(windowMs).toISOString();
56
+ }
57
+ /** The most recent window at or before `nowMs`, or null when the schedule has
58
+ * none. `nextWindowAfter` only ever looks FORWARD, so asking it from
59
+ * `nowMs - one period` answers the previous window whenever `nowMs` sits
60
+ * exactly on a boundary, and a daily schedule read after its minute answers
61
+ * TOMORROW. Both schedule kinds have a fixed period, so stepping one period
62
+ * back off the next window is exact. */
63
+ function latestWindowAtOrBefore(schedule, nowMs) {
64
+ if (unfireableScheduleReason(schedule) !== null) return null;
65
+ const next = (0, _receptron_task_scheduler.nextWindowAfter)(toLibrarySchedule(schedule), nowMs);
66
+ if (next === null || !Number.isFinite(next)) return null;
67
+ if (next <= nowMs) return next;
68
+ return next - (schedule.type === _receptron_task_scheduler.SCHEDULE_TYPES.interval ? schedule.intervalMs : ONE_DAY_MS);
69
+ }
70
+ /** Name the field that makes a schedule unfireable, or null when it is fine.
71
+ * Returns the offending value (not a boolean) so the caller can put it in the
72
+ * log — a task that silently never runs leaves no evidence to start from
73
+ * (#2765). */
74
+ function unfireableScheduleReason(schedule) {
75
+ if (schedule.type === _receptron_task_scheduler.SCHEDULE_TYPES.interval) return isUsableInterval(schedule.intervalMs) ? null : {
76
+ field: "intervalMs",
77
+ value: String(schedule.intervalMs)
78
+ };
79
+ return dailyOffsetMs(schedule.time) !== null ? null : {
80
+ field: "time",
81
+ value: schedule.time
82
+ };
83
+ }
84
+ //#endregion
85
+ //#region src/scheduler/task-manager.ts
86
+ var ONE_SECOND_MS = 1e3;
87
+ var ONE_MINUTE_MS = 60 * ONE_SECOND_MS;
88
+ var DEFAULT_FIRING_STAGGER_MS = ONE_SECOND_MS;
14
89
  var MAX_STAGGER_FRACTION_OF_TICK = .5;
15
90
  var realSleep = (delayMs) => new Promise((resolve) => setTimeout(resolve, delayMs));
16
91
  function staggerStepMs(staggerMs, tickMs, count) {
@@ -24,34 +99,7 @@ var NOOP_LOG$1 = {
24
99
  error: () => {}
25
100
  };
26
101
  function isDue(now, schedule, tickMs) {
27
- if (schedule.type === _receptron_task_scheduler.SCHEDULE_TYPES.interval) {
28
- const msSinceMidnight = now.getUTCHours() * ONE_HOUR_MS + now.getUTCMinutes() * ONE_MINUTE_MS + now.getUTCSeconds() * ONE_SECOND_MS$1;
29
- return Math.floor(msSinceMidnight / tickMs) * tickMs % schedule.intervalMs === 0;
30
- }
31
- if (schedule.type === _receptron_task_scheduler.SCHEDULE_TYPES.daily) {
32
- const targetMs = dailyTargetMs(schedule.time);
33
- if (targetMs === null) return false;
34
- const msSinceMidnight = now.getUTCHours() * ONE_HOUR_MS + now.getUTCMinutes() * ONE_MINUTE_MS + now.getUTCSeconds() * ONE_SECOND_MS$1;
35
- return Math.floor(msSinceMidnight / tickMs) * tickMs === targetMs;
36
- }
37
- return false;
38
- }
39
- /** Milliseconds past UTC midnight for a `HH:MM` daily time, or null when the
40
- * string isn't that shape. `TaskSchedule.time` is a bare `string` on a
41
- * published package, so a host that skips its own validation must land on
42
- * "never due" rather than on a garbage firing time. */
43
- function dailyTargetMs(time) {
44
- const [hours, minutes] = time.split(":").map(Number);
45
- if (hours === void 0 || minutes === void 0) return null;
46
- if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null;
47
- return hours * ONE_HOUR_MS + minutes * ONE_MINUTE_MS;
48
- }
49
- /** The `time` of a daily schedule this manager can never fire, or null when the
50
- * schedule is fine. Returning the offending value (not a boolean) is what lets
51
- * the caller name it in the log. */
52
- function unfireableDailyTime(schedule) {
53
- if (schedule.type !== _receptron_task_scheduler.SCHEDULE_TYPES.daily) return null;
54
- return dailyTargetMs(schedule.time) === null ? schedule.time : null;
102
+ return isScheduleDueAt(schedule, now.getTime(), tickMs);
55
103
  }
56
104
  /** Say out loud that this schedule can never fire. The task is still accepted —
57
105
  * `isDue` answers false forever, which is the safe outcome — but silence here
@@ -59,11 +107,11 @@ function unfireableDailyTime(schedule) {
59
107
  * evidence anywhere to start from (#2765). Deliberately not a throw: a
60
108
  * consumer whose task has been quietly dead would get a boot crash instead. */
61
109
  function reportUnfireable(log, taskId, schedule) {
62
- const time = unfireableDailyTime(schedule);
63
- if (time === null) return;
64
- log.error("daily time is not HH:MM — this task will never run", {
110
+ const reason = unfireableScheduleReason(schedule);
111
+ if (reason === null) return;
112
+ log.error(`schedule has an unusable ${reason.field} — this task will never run`, {
65
113
  id: taskId,
66
- time
114
+ [reason.field]: reason.value
67
115
  });
68
116
  }
69
117
  /** Split the due tasks into those that may run immediately and those gated
@@ -206,7 +254,6 @@ function createTaskManager(options) {
206
254
  }
207
255
  //#endregion
208
256
  //#region src/scheduler/adapter.ts
209
- var ONE_SECOND_MS = 1e3;
210
257
  var SCHEDULER_CONFIG_DIR = "config/scheduler";
211
258
  var SCHEDULER_DATA_DIR = "data/scheduler/logs";
212
259
  var NOOP_LOG = {
@@ -259,14 +306,7 @@ async function initScheduler(taskManager, tasks) {
259
306
  systemTasks.length = 0;
260
307
  systemTasks.push(...tasks);
261
308
  taskManagerRef = taskManager;
262
- const catchUpTasks = tasks.map((taskDef) => ({
263
- id: taskDef.id,
264
- name: taskDef.name,
265
- schedule: toCoreSchedule(taskDef.schedule),
266
- missedRunPolicy: taskDef.missedRunPolicy,
267
- enabled: true
268
- }));
269
- const plan = (0, _receptron_task_scheduler.computeCatchUpPlan)(catchUpTasks, stateMap, Date.now());
309
+ const plan = (0, _receptron_task_scheduler.computeCatchUpPlan)(catchUpTasksFor(tasks), stateMap, Date.now());
270
310
  for (const skip of plan.skipped) {
271
311
  logger().info("catch-up skipped", {
272
312
  taskId: skip.taskId,
@@ -286,8 +326,8 @@ async function initScheduler(taskManager, tasks) {
286
326
  id: task.id,
287
327
  description: task.description,
288
328
  schedule: task.schedule,
289
- run: async () => {
290
- const windowIso = computeCurrentWindow(task);
329
+ run: async (ctx) => {
330
+ const windowIso = computeCurrentWindow(task, ctx.now.getTime());
291
331
  await executeAndLog(task, windowIso, _receptron_task_scheduler.TASK_TRIGGERS.scheduled);
292
332
  }
293
333
  });
@@ -296,6 +336,28 @@ async function initScheduler(taskManager, tasks) {
296
336
  stateEntries: stateMap.size
297
337
  });
298
338
  }
339
+ /** The catch-up input, with the tasks that can never fire left out. Their
340
+ * windows come back NaN rather than null, which `listMissedWindows` cannot
341
+ * see the end of — it fills to its cap and the first `new Date(NaN)` throws
342
+ * `RangeError`, taking every other task's catch-up down with it at startup.
343
+ * Registration still happens, so the task-manager reports the bad schedule. */
344
+ function catchUpTasksFor(tasks) {
345
+ return tasks.filter((taskDef) => {
346
+ const reason = unfireableScheduleReason(taskDef.schedule);
347
+ if (reason === null) return true;
348
+ logger().error(`schedule has an unusable ${reason.field} — skipping catch-up, this task will never run`, {
349
+ taskId: taskDef.id,
350
+ [reason.field]: reason.value
351
+ });
352
+ return false;
353
+ }).map((taskDef) => ({
354
+ id: taskDef.id,
355
+ name: taskDef.name,
356
+ schedule: toLibrarySchedule(taskDef.schedule),
357
+ missedRunPolicy: taskDef.missedRunPolicy,
358
+ enabled: true
359
+ }));
360
+ }
299
361
  /** Apply a schedule override to a running system task. Updates the
300
362
  * in-memory task definition, the task-manager, and recalculates
301
363
  * nextScheduledAt in persisted state. */
@@ -449,24 +511,15 @@ async function safeUpdateState(taskId, patch) {
449
511
  /** Compute the window boundary that the current tick belongs to. For
450
512
  * scheduled runs, this is the epoch-aligned window — not the wall-clock
451
513
  * time of execution. This keeps lastRunAt consistent with catch-up's
452
- * window-based accounting. */
453
- function computeCurrentWindow(task) {
454
- const coreSchedule = toCoreSchedule(task.schedule);
455
- const nowMs = Date.now();
456
- const windowMs = (0, _receptron_task_scheduler.nextWindowAfter)(coreSchedule, nowMs - (coreSchedule.type === _receptron_task_scheduler.SCHEDULE_TYPES.interval ? coreSchedule.intervalSec * ONE_SECOND_MS : 0));
457
- return windowMs !== null && windowMs <= nowMs ? new Date(windowMs).toISOString() : new Date(nowMs).toISOString();
514
+ * window-based accounting. `tickMs` is the tick's own clock, not
515
+ * `Date.now()`: the two drift apart by however long the tick took to reach
516
+ * this task, and under an injected clock they are unrelated. */
517
+ function computeCurrentWindow(task, tickMs) {
518
+ return windowToIso(latestWindowAtOrBefore(task.schedule, tickMs)) ?? new Date(tickMs).toISOString();
458
519
  }
459
520
  function computeNextScheduledFor(schedule) {
460
- const coreSchedule = toCoreSchedule(schedule);
461
- const next = (0, _receptron_task_scheduler.nextWindowAfter)(coreSchedule, Date.now() + 1);
462
- return next !== null ? new Date(next).toISOString() : null;
463
- }
464
- function toCoreSchedule(schedule) {
465
- if (schedule.type === _receptron_task_scheduler.SCHEDULE_TYPES.interval) return {
466
- type: _receptron_task_scheduler.SCHEDULE_TYPES.interval,
467
- intervalSec: Math.round(schedule.intervalMs / ONE_SECOND_MS)
468
- };
469
- return schedule;
521
+ if (unfireableScheduleReason(schedule) !== null) return null;
522
+ return windowToIso((0, _receptron_task_scheduler.nextWindowAfter)(toLibrarySchedule(schedule), Date.now() + 1));
470
523
  }
471
524
  //#endregion
472
525
  Object.defineProperty(exports, "TASK_TRIGGERS", {
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":[],"sources":["../../src/scheduler/task-manager.ts","../../src/scheduler/adapter.ts"],"sourcesContent":["// Generic dependency-ordered cron tick engine. Host-agnostic: the only\n// host coupling (a logger) is injected via options. Schedules are either\n// fixed intervals or a daily UTC time; tasks may declare a `dependsOn`\n// edge so an ordering like \"news fetch → journal → memory extraction\"\n// runs in sequence within one tick.\n\nimport type { MinimalLogger } from \"@mulmoclaude/common\";\nimport { SCHEDULE_TYPES } from \"@receptron/task-scheduler\";\n\nconst ONE_SECOND_MS = 1000;\nconst ONE_MINUTE_MS = 60 * ONE_SECOND_MS;\nconst ONE_HOUR_MS = 60 * ONE_MINUTE_MS;\n\n// Gap between the START of each independently-due task within one tick. When\n// many tasks come due at the same minute (system journal + feed-refresh + a few\n// user tasks all at 20:00 UTC), firing every chat in the same event-loop turn\n// floods the machine; the mulmoclaude MCP broker each chat spawns then boots\n// under contention and can lose the startup race to the CLI's first tool call,\n// so that turn fails with `handlePermission not found` (#2057). Spacing the\n// launches by a second gives each broker room to connect. Far under one tick\n// (a handful of tasks spread over a few seconds), so nothing is delayed past\n// its window.\nconst DEFAULT_FIRING_STAGGER_MS = ONE_SECOND_MS;\n\n// The total stagger must stay well inside one tick, or the tail tasks start in a\n// LATER tick window and two ticks overlap. Cap all starts to this fraction of\n// `tickMs` regardless of task count or the configured gap — this keeps a debug\n// `tickMs === firingStaggerMs` (see server boot) from degenerating.\nconst MAX_STAGGER_FRACTION_OF_TICK = 0.5;\n\nconst realSleep = (delayMs: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, delayMs));\n\n// Per-task stagger step: the configured gap, shrunk so the last of `count` tasks\n// still starts within MAX_STAGGER_FRACTION_OF_TICK of the tick. 0 disables it.\nfunction staggerStepMs(staggerMs: number, tickMs: number, count: number): number {\n if (staggerMs <= 0 || count <= 1) return 0;\n const maxStepMs = (tickMs * MAX_STAGGER_FRACTION_OF_TICK) / (count - 1);\n return Math.min(staggerMs, maxStepMs);\n}\n\n/** Minimal logger the engine logs through. Absent one, runs silent. */\nexport type SchedulerLogger = MinimalLogger;\n\nconst NOOP_LOG: SchedulerLogger = { info: () => {}, warn: () => {}, error: () => {} };\n\nexport type TaskSchedule = { type: typeof SCHEDULE_TYPES.interval; intervalMs: number } | { type: typeof SCHEDULE_TYPES.daily; time: string }; // time: \"HH:MM\" in UTC\n\nexport interface TaskRunContext {\n taskId: string;\n now: Date;\n}\n\nexport interface TaskDefinition {\n id: string;\n description?: string;\n schedule: TaskSchedule;\n enabled?: boolean; // default: true\n /** If set, this task only fires after the named task has completed\n * successfully in the current tick cycle. Enforces ordering like\n * \"news fetch → journal → memory extraction\". */\n dependsOn?: string;\n run: (ctx: TaskRunContext) => Promise<void>;\n}\n\nexport interface TaskSummary {\n id: string;\n description?: string | undefined;\n schedule: TaskSchedule;\n dependsOn?: string | undefined;\n}\n\nexport interface ITaskManager {\n registerTask: (def: TaskDefinition) => void;\n removeTask: (taskId: string) => void;\n /** Update the schedule of an existing task. Returns false if not found. */\n updateSchedule: (taskId: string, schedule: TaskSchedule) => boolean;\n start: () => void;\n stop: () => void;\n /** Run one tick manually (for testing). */\n tick: () => Promise<void>;\n listTasks: () => TaskSummary[];\n}\n\nexport interface TaskManagerOptions {\n tickMs?: number; // default: ONE_MINUTE_MS\n now?: () => Date; // default: () => new Date()\n log?: SchedulerLogger; // default: noop\n /** Gap between the start of each independently-due task in a tick (#2057).\n * Default DEFAULT_FIRING_STAGGER_MS; 0 fires them all at once. */\n firingStaggerMs?: number;\n /** Injected so tests advance time without real timers. Default setTimeout. */\n sleep?: (delayMs: number) => Promise<void>;\n}\n\nfunction isDue(now: Date, schedule: TaskSchedule, tickMs: number): boolean {\n if (schedule.type === SCHEDULE_TYPES.interval) {\n const msSinceMidnight = now.getUTCHours() * ONE_HOUR_MS + now.getUTCMinutes() * ONE_MINUTE_MS + now.getUTCSeconds() * ONE_SECOND_MS;\n // Round down to tick boundary, then check if it aligns with the interval\n const rounded = Math.floor(msSinceMidnight / tickMs) * tickMs;\n return rounded % schedule.intervalMs === 0;\n }\n\n if (schedule.type === SCHEDULE_TYPES.daily) {\n const targetMs = dailyTargetMs(schedule.time);\n if (targetMs === null) return false;\n const msSinceMidnight = now.getUTCHours() * ONE_HOUR_MS + now.getUTCMinutes() * ONE_MINUTE_MS + now.getUTCSeconds() * ONE_SECOND_MS;\n const rounded = Math.floor(msSinceMidnight / tickMs) * tickMs;\n return rounded === targetMs;\n }\n\n return false;\n}\n\n/** Milliseconds past UTC midnight for a `HH:MM` daily time, or null when the\n * string isn't that shape. `TaskSchedule.time` is a bare `string` on a\n * published package, so a host that skips its own validation must land on\n * \"never due\" rather than on a garbage firing time. */\nfunction dailyTargetMs(time: string): number | null {\n const [hours, minutes] = time.split(\":\").map(Number);\n if (hours === undefined || minutes === undefined) return null;\n if (!Number.isFinite(hours) || !Number.isFinite(minutes)) return null;\n return hours * ONE_HOUR_MS + minutes * ONE_MINUTE_MS;\n}\n\n/** The `time` of a daily schedule this manager can never fire, or null when the\n * schedule is fine. Returning the offending value (not a boolean) is what lets\n * the caller name it in the log. */\nfunction unfireableDailyTime(schedule: TaskSchedule): string | null {\n if (schedule.type !== SCHEDULE_TYPES.daily) return null;\n return dailyTargetMs(schedule.time) === null ? schedule.time : null;\n}\n\n/** Say out loud that this schedule can never fire. The task is still accepted —\n * `isDue` answers false forever, which is the safe outcome — but silence here\n * is what made \"the task I scheduled has never run once\" a bug with no\n * evidence anywhere to start from (#2765). Deliberately not a throw: a\n * consumer whose task has been quietly dead would get a boot crash instead. */\nfunction reportUnfireable(log: SchedulerLogger, taskId: string, schedule: TaskSchedule): void {\n const time = unfireableDailyTime(schedule);\n if (time === null) return;\n log.error(\"daily time is not HH:MM — this task will never run\", { id: taskId, time });\n}\n\n/** Split the due tasks into those that may run immediately and those gated\n * behind a `dependsOn` edge (resolved later in the same tick cycle). */\nexport function collectDueTasks(\n currentTime: Date,\n registry: Map<string, TaskDefinition>,\n tickMs: number,\n): { independent: TaskDefinition[]; dependent: TaskDefinition[] } {\n const independent: TaskDefinition[] = [];\n const dependent: TaskDefinition[] = [];\n for (const def of registry.values()) {\n if (def.enabled === false) continue;\n if (!isDue(currentTime, def.schedule, tickMs)) continue;\n if (def.dependsOn) {\n dependent.push(def);\n } else {\n independent.push(def);\n }\n }\n return { independent, dependent };\n}\n\nasync function runAndTrack(def: TaskDefinition, currentTime: Date, succeeded: Set<string>, log: SchedulerLogger): Promise<void> {\n try {\n await def.run({ taskId: def.id, now: currentTime });\n succeeded.add(def.id);\n } catch (err) {\n log.error(\"task failed\", {\n id: def.id,\n error: String(err),\n });\n }\n}\n\nasync function runDependentChain(dependent: TaskDefinition[], currentTime: Date, succeeded: Set<string>, log: SchedulerLogger): Promise<void> {\n let remaining = [...dependent];\n let progress = true;\n while (remaining.length > 0 && progress) {\n progress = false;\n const next: TaskDefinition[] = [];\n for (const def of remaining) {\n const dep = def.dependsOn;\n if (!dep || !succeeded.has(dep)) {\n next.push(def);\n continue;\n }\n await runAndTrack(def, currentTime, succeeded, log);\n progress = true;\n }\n remaining = next;\n }\n}\n\ninterface TickConfig {\n tickMs: number;\n staggerMs: number;\n sleep: (delayMs: number) => Promise<void>;\n log: SchedulerLogger;\n}\n\nasync function runTick(now: () => Date, registry: Map<string, TaskDefinition>, cfg: TickConfig): Promise<void> {\n const currentTime = now();\n const { independent, dependent } = collectDueTasks(currentTime, registry, cfg.tickMs);\n\n // Per-invocation set — success does not leak across tick() calls.\n const succeeded = new Set<string>();\n\n // Staggered start (#2057), still concurrent: each fires after its own capped\n // delay but the tick awaits them all, preserving the previous \"all due tasks\n // ran this tick\" contract.\n const stepMs = staggerStepMs(cfg.staggerMs, cfg.tickMs, independent.length);\n await Promise.all(\n independent.map(async (def, index) => {\n if (stepMs > 0 && index > 0) await cfg.sleep(index * stepMs);\n await runAndTrack(def, currentTime, succeeded, cfg.log);\n }),\n );\n\n await runDependentChain(dependent, currentTime, succeeded, cfg.log);\n}\n\nexport function listTaskSummaries(registry: Map<string, TaskDefinition>): TaskSummary[] {\n return [...registry.values()].map((taskDef) => ({\n id: taskDef.id,\n description: taskDef.description,\n schedule: taskDef.schedule,\n dependsOn: taskDef.dependsOn,\n }));\n}\n\n// A tick runner that skips re-entry: if the previous tick is still draining its\n// staggered starts, drop this one so a slow tick + short tickMs can never run\n// two ticks concurrently.\nfunction makeGuardedTick(now: () => Date, registry: Map<string, TaskDefinition>, cfg: TickConfig): () => Promise<void> {\n let ticking = false;\n return async () => {\n if (ticking) return;\n ticking = true;\n try {\n await runTick(now, registry, cfg);\n } finally {\n ticking = false;\n }\n };\n}\n\nfunction resolveTickConfig(options?: TaskManagerOptions): { tickMs: number; now: () => Date; cfg: TickConfig } {\n const tickMs = options?.tickMs ?? ONE_MINUTE_MS;\n return {\n tickMs,\n now: options?.now ?? (() => new Date()),\n cfg: {\n tickMs,\n staggerMs: options?.firingStaggerMs ?? DEFAULT_FIRING_STAGGER_MS,\n sleep: options?.sleep ?? realSleep,\n log: options?.log ?? NOOP_LOG,\n },\n };\n}\n\nexport function createTaskManager(options?: TaskManagerOptions): ITaskManager {\n const { tickMs, now, cfg } = resolveTickConfig(options);\n const { log } = cfg;\n const registry = new Map<string, TaskDefinition>();\n let timer: ReturnType<typeof setInterval> | null = null;\n const onTick = makeGuardedTick(now, registry, cfg);\n\n return {\n async tick() {\n await onTick();\n },\n\n registerTask(def: TaskDefinition) {\n if (registry.has(def.id)) {\n throw new Error(`[task-manager] Task \"${def.id}\" is already registered`);\n }\n reportUnfireable(log, def.id, def.schedule);\n registry.set(def.id, def);\n log.info(\"registered\", { id: def.id });\n },\n\n updateSchedule(taskId: string, schedule: TaskSchedule): boolean {\n const def = registry.get(taskId);\n if (!def) return false;\n // Checked here as well as at registration: an override applied at run\n // time (`applyScheduleOverride`) never passes through `registerTask`.\n reportUnfireable(log, taskId, schedule);\n def.schedule = schedule;\n log.info(\"schedule updated\", { id: taskId });\n return true;\n },\n\n removeTask(taskId: string) {\n if (registry.delete(taskId)) {\n log.info(\"removed\", { id: taskId });\n }\n },\n\n start() {\n if (timer) return;\n // `onTick` guards re-entry but not failure — it has a `finally`, no\n // `catch` — so handing it straight to setInterval let a rejected tick\n // escape as an unhandled rejection, which the host turns into a process\n // exit. The scheduler must outlive one bad tick.\n timer = setInterval(() => {\n onTick().catch((err: unknown) => log.error(\"tick failed\", { error: String(err) }));\n }, tickMs);\n log.info(\"started\", { tickMs });\n },\n\n stop() {\n if (timer) {\n clearInterval(timer);\n timer = null;\n log.info(\"stopped\");\n }\n },\n\n listTasks() {\n return listTaskSummaries(registry);\n },\n };\n}\n","// Adapter that wires the pure scheduler library (@receptron/task-scheduler)\n// to a host's task-manager + workspace. Registers system tasks, runs\n// catch-up on startup, and persists execution state + logs.\n//\n// Host-agnostic: the workspace root, the atomic file writer, and the\n// logger are injected via `configureScheduler`. The host supplies its OWN\n// system tasks (journal / feeds / user-cron in MulmoClaude) to\n// `initScheduler` — the package owns no task definitions. Deliberately\n// thin: all complex scheduling logic lives in @receptron/task-scheduler.\n\nimport { existsSync } from \"node:fs\";\nimport { readFile, appendFile, mkdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n type TaskSchedule,\n type TaskExecutionState,\n type TaskLogEntry,\n type CatchUpTask,\n type TaskTrigger,\n emptyState,\n computeCatchUpPlan,\n nextWindowAfter,\n loadState,\n updateAndSave,\n appendLogEntry,\n queryLog,\n SCHEDULE_TYPES,\n TASK_RESULTS,\n TASK_TRIGGERS,\n type MISSED_RUN_POLICIES,\n type StateMap,\n type StateDeps,\n type LogDeps,\n} from \"@receptron/task-scheduler\";\nimport type { ITaskManager, TaskDefinition, SchedulerLogger } from \"./task-manager.js\";\nimport { errorMessage } from \"../utils/errors.js\";\n\nconst ONE_SECOND_MS = 1000;\nconst SCHEDULER_CONFIG_DIR = \"config/scheduler\";\nconst SCHEDULER_DATA_DIR = \"data/scheduler/logs\";\n\n// ── Host injection ────────────────────────────────────────────────\n\nexport interface SchedulerConfig {\n /** Absolute workspace root — state.json + logs hang off it. */\n workspaceRoot: string;\n /** Host atomic file writer (used with `uniqueTmp` for the state file). */\n writeFileAtomic: (filePath: string, content: string, opts: { uniqueTmp: boolean }) => Promise<void>;\n /** Optional logger. */\n log?: SchedulerLogger;\n}\n\nconst NOOP_LOG: SchedulerLogger = { info: () => {}, warn: () => {}, error: () => {} };\n\nlet config: SchedulerConfig | null = null;\n\n/** Wire the adapter to a host. Call once at startup, before `initScheduler`. */\nexport function configureScheduler(injected: SchedulerConfig): void {\n config = injected;\n}\n\nfunction requireConfig(): SchedulerConfig {\n if (!config) throw new Error(\"scheduler: configureScheduler() not called\");\n return config;\n}\n\nfunction logger(): SchedulerLogger {\n return config?.log ?? NOOP_LOG;\n}\n\n// ── Paths ─────────────────────────────────────────────────────────\n\nfunction stateFilePath(): string {\n return path.join(requireConfig().workspaceRoot, SCHEDULER_CONFIG_DIR, \"state.json\");\n}\n\nfunction logsDir(): string {\n return path.join(requireConfig().workspaceRoot, SCHEDULER_DATA_DIR);\n}\n\n// ── I/O deps (real filesystem) ────────────────────────────────────\n\nfunction stateDeps(): StateDeps {\n return {\n readFile: (filePath: string) => readFile(filePath, \"utf-8\"),\n writeFileAtomic: (filePath: string, content: string) => requireConfig().writeFileAtomic(filePath, content, { uniqueTmp: true }),\n exists: existsSync,\n };\n}\n\nconst logDeps: LogDeps = {\n appendFile: (filePath: string, content: string) => appendFile(filePath, content),\n readFile: (filePath: string) => readFile(filePath, \"utf-8\"),\n exists: existsSync,\n ensureDir: (directoryPath: string) => mkdir(directoryPath, { recursive: true }).then(() => {}),\n};\n\n// ── System task registry ──────────────────────────────────────────\n\nexport interface SystemTaskDef {\n id: string;\n name: string;\n description: string;\n schedule: TaskDefinition[\"schedule\"];\n missedRunPolicy: typeof MISSED_RUN_POLICIES.skip | typeof MISSED_RUN_POLICIES.runOnce | typeof MISSED_RUN_POLICIES.runAll;\n run: () => Promise<void>;\n}\n\n// ── Public API ────────────────────────────────────────────────────\n\nlet stateMap: StateMap = new Map();\nconst systemTasks: SystemTaskDef[] = [];\nlet taskManagerRef: ITaskManager | null = null;\n\n/**\n * Initialize the scheduler adapter. Call once at server startup AFTER the\n * task-manager is created but BEFORE `taskManager.start()`.\n */\nexport async function initScheduler(taskManager: ITaskManager, tasks: SystemTaskDef[]): Promise<void> {\n await mkdir(path.dirname(stateFilePath()), { recursive: true });\n await mkdir(logsDir(), { recursive: true });\n\n stateMap = await loadState(stateFilePath(), stateDeps());\n systemTasks.length = 0;\n systemTasks.push(...tasks);\n taskManagerRef = taskManager;\n\n // Run catch-up\n const catchUpTasks: CatchUpTask[] = tasks.map((taskDef) => ({\n id: taskDef.id,\n name: taskDef.name,\n schedule: toCoreSchedule(taskDef.schedule),\n missedRunPolicy: taskDef.missedRunPolicy,\n enabled: true,\n }));\n const plan = computeCatchUpPlan(catchUpTasks, stateMap, Date.now());\n\n for (const skip of plan.skipped) {\n logger().info(\"catch-up skipped\", { taskId: skip.taskId, windows: skip.windowCount });\n await safeUpdateState(skip.taskId, { lastRunAt: skip.lastWindow });\n }\n\n if (plan.runs.length > 0) {\n logger().info(\"catch-up enqueued\", { runs: plan.runs.length });\n for (const run of plan.runs) {\n const task = tasks.find((taskDef) => taskDef.id === run.taskId);\n if (!task) continue;\n await executeAndLog(task, run.context.scheduledFor, TASK_TRIGGERS.catchUp);\n }\n }\n\n // Register with task-manager for ongoing ticks\n for (const task of tasks) {\n taskManager.registerTask({\n id: task.id,\n description: task.description,\n schedule: task.schedule,\n run: async () => {\n const windowIso = computeCurrentWindow(task);\n await executeAndLog(task, windowIso, TASK_TRIGGERS.scheduled);\n },\n });\n }\n\n logger().info(\"initialized\", { tasks: tasks.map((taskDef) => taskDef.id), stateEntries: stateMap.size });\n}\n\n/** Apply a schedule override to a running system task. Updates the\n * in-memory task definition, the task-manager, and recalculates\n * nextScheduledAt in persisted state. */\nexport async function applyScheduleOverride(taskId: string, schedule: SystemTaskDef[\"schedule\"]): Promise<boolean> {\n const task = systemTasks.find((taskDef) => taskDef.id === taskId);\n if (!task || !taskManagerRef) return false;\n if (!taskManagerRef.updateSchedule(taskId, schedule)) return false;\n task.schedule = schedule;\n\n // Recalculate next window so the UI reflects the new schedule\n const nextScheduledAt = computeNextScheduledFor(task.schedule);\n await safeUpdateState(taskId, { nextScheduledAt });\n\n return true;\n}\n\n/** Query execution logs — used by API routes. */\nexport async function getSchedulerLogs(opts: { since?: string | undefined; taskId?: string | undefined; limit?: number | undefined }): Promise<TaskLogEntry[]> {\n return queryLog(logsDir(), opts, logDeps);\n}\n\n/** Get all task states — used by API routes. */\nexport function getSchedulerTasks(): {\n id: string;\n name: string;\n description: string;\n schedule: TaskDefinition[\"schedule\"];\n missedRunPolicy: string;\n state: TaskExecutionState;\n}[] {\n return systemTasks.map((taskDef) => ({\n id: taskDef.id,\n name: taskDef.name,\n description: taskDef.description,\n schedule: taskDef.schedule,\n missedRunPolicy: taskDef.missedRunPolicy,\n state: stateMap.get(taskDef.id) ?? emptyState(taskDef.id),\n }));\n}\n\n/** Read the persisted execution state for any task id (system, user, or\n * skill). Returns an empty state when the id has never run — used by the API\n * route to attach last-run / next-run / history state to user + skill tasks\n * it lists from other sources. */\nexport function getSchedulerTaskState(taskId: string): TaskExecutionState {\n return stateMap.get(taskId) ?? emptyState(taskId);\n}\n\n/** Record a run of an EXTERNAL (skill / user) task — one registered directly\n * on the task-manager rather than through `initScheduler`. Persists a log\n * entry + updates state so these tasks get the same history / last-run /\n * next-run as system tasks. Because they are fire-and-forget (`startChat`\n * spawns an async chat), `errorMessage` reflects whether the *dispatch*\n * succeeded, not the chat's eventual outcome; `chatSessionId` links the run\n * to the spawned session. */\nexport async function recordExternalRun(params: {\n id: string;\n name: string;\n schedule: TaskDefinition[\"schedule\"];\n scheduledFor: string;\n startedAt: string;\n durationMs: number;\n trigger: TaskTrigger;\n errorMessage: string | null;\n chatSessionId?: string | undefined;\n}): Promise<void> {\n await persistRun({\n meta: { id: params.id, name: params.name, schedule: params.schedule },\n scheduledFor: params.scheduledFor,\n startedAt: params.startedAt,\n durationMs: params.durationMs,\n trigger: params.trigger,\n errMsg: params.errorMessage,\n chatSessionId: params.chatSessionId,\n });\n}\n\n/** Test-only: clear config + in-memory state. */\nexport function resetSchedulerForTesting(): void {\n config = null;\n stateMap = new Map();\n systemTasks.length = 0;\n taskManagerRef = null;\n}\n\n// ── Internal ──────────────────────────────────────────────────────\n\nasync function executeAndLog(task: SystemTaskDef, scheduledFor: string, trigger: TaskTrigger): Promise<void> {\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n let errMsg: string | null = null;\n try {\n await task.run();\n } catch (err) {\n errMsg = errorMessage(err);\n logger().error(\"task failed\", { taskId: task.id, error: errMsg });\n }\n const durationMs = Date.now() - startMs;\n // Persistence is best-effort — never let disk failures propagate to the\n // tick loop or abort startup catch-up.\n await persistRun({ meta: { id: task.id, name: task.name, schedule: task.schedule }, scheduledFor, startedAt, durationMs, trigger, errMsg });\n}\n\n/** The minimum a run needs to persist state + a log entry — shared by system\n * tasks (`executeAndLog`) and external skill/user runs (`recordExternalRun`). */\ninterface TaskRunMeta {\n id: string;\n name: string;\n schedule: TaskDefinition[\"schedule\"];\n}\n\ninterface RunRecord {\n meta: TaskRunMeta;\n scheduledFor: string;\n startedAt: string;\n durationMs: number;\n trigger: TaskTrigger;\n errMsg: string | null;\n chatSessionId?: string | undefined;\n}\n\n/** Best-effort persistence — state and log are independent, so one failing\n * never blocks the other and neither propagates upward. */\nasync function persistRun(run: RunRecord): Promise<void> {\n await writeRunState(run);\n await writeRunLog(run);\n}\n\nasync function writeRunState(run: RunRecord): Promise<void> {\n const { meta, scheduledFor, durationMs, errMsg } = run;\n const isSuccess = errMsg === null;\n const currentState = stateMap.get(meta.id);\n try {\n await updateAndSave(\n stateFilePath(),\n stateMap,\n meta.id,\n {\n lastRunAt: scheduledFor,\n lastRunResult: isSuccess ? TASK_RESULTS.success : TASK_RESULTS.error,\n lastRunDurationMs: durationMs,\n lastErrorMessage: errMsg,\n consecutiveFailures: isSuccess ? 0 : (currentState?.consecutiveFailures ?? 0) + 1,\n totalRuns: (currentState?.totalRuns ?? 0) + 1,\n nextScheduledAt: computeNextScheduledFor(meta.schedule),\n },\n stateDeps(),\n );\n } catch (err) {\n logger().warn(\"state persistence failed\", { taskId: meta.id, error: String(err) });\n }\n}\n\nasync function writeRunLog(run: RunRecord): Promise<void> {\n const { meta, scheduledFor, startedAt, durationMs, trigger, errMsg, chatSessionId } = run;\n const isSuccess = errMsg === null;\n try {\n await appendLogEntry(\n logsDir(),\n {\n taskId: meta.id,\n taskName: meta.name,\n scheduledFor,\n startedAt,\n completedAt: new Date().toISOString(),\n result: isSuccess ? TASK_RESULTS.success : TASK_RESULTS.error,\n durationMs,\n trigger,\n ...(errMsg !== null && { errorMessage: errMsg }),\n ...(chatSessionId !== undefined && { chatSessionId }),\n },\n logDeps,\n );\n } catch (err) {\n logger().warn(\"log persistence failed\", { taskId: meta.id, error: String(err) });\n }\n}\n\n/** Safe state update — swallows errors. */\nasync function safeUpdateState(taskId: string, patch: Partial<TaskExecutionState>): Promise<void> {\n try {\n await updateAndSave(stateFilePath(), stateMap, taskId, patch, stateDeps());\n } catch (err) {\n logger().warn(\"state update failed\", { taskId, error: String(err) });\n }\n}\n\n/** Compute the window boundary that the current tick belongs to. For\n * scheduled runs, this is the epoch-aligned window — not the wall-clock\n * time of execution. This keeps lastRunAt consistent with catch-up's\n * window-based accounting. */\nfunction computeCurrentWindow(task: SystemTaskDef): string {\n const coreSchedule = toCoreSchedule(task.schedule);\n // The window that just fired is the latest one at or before now.\n const nowMs = Date.now();\n const windowMs = nextWindowAfter(coreSchedule, nowMs - (coreSchedule.type === SCHEDULE_TYPES.interval ? coreSchedule.intervalSec * ONE_SECOND_MS : 0));\n return windowMs !== null && windowMs <= nowMs ? new Date(windowMs).toISOString() : new Date(nowMs).toISOString();\n}\n\nfunction computeNextScheduledFor(schedule: TaskDefinition[\"schedule\"]): string | null {\n const coreSchedule = toCoreSchedule(schedule);\n const next = nextWindowAfter(coreSchedule, Date.now() + 1);\n return next !== null ? new Date(next).toISOString() : null;\n}\n\nfunction toCoreSchedule(schedule: TaskDefinition[\"schedule\"]): TaskSchedule {\n if (schedule.type === SCHEDULE_TYPES.interval) {\n return {\n type: SCHEDULE_TYPES.interval,\n intervalSec: Math.round(schedule.intervalMs / ONE_SECOND_MS),\n };\n }\n return schedule;\n}\n"],"mappings":";;;;;;;;;AASA,IAAM,kBAAgB;AACtB,IAAM,gBAAgB,KAAK;AAC3B,IAAM,cAAc,KAAK;AAWzB,IAAM,4BAA4B;AAMlC,IAAM,+BAA+B;AAErC,IAAM,aAAa,YAAmC,IAAI,SAAS,YAAY,WAAW,SAAS,OAAO,CAAC;AAI3G,SAAS,cAAc,WAAmB,QAAgB,OAAuB;CAC/E,IAAI,aAAa,KAAK,SAAS,GAAG,OAAO;CACzC,MAAM,YAAa,SAAS,gCAAiC,QAAQ;CACrE,OAAO,KAAK,IAAI,WAAW,SAAS;AACtC;AAKA,IAAM,aAA4B;CAAE,YAAY,CAAC;CAAG,YAAY,CAAC;CAAG,aAAa,CAAC;AAAE;AAmDpF,SAAS,MAAM,KAAW,UAAwB,QAAyB;CACzE,IAAI,SAAS,SAAS,0BAAA,eAAe,UAAU;EAC7C,MAAM,kBAAkB,IAAI,YAAY,IAAI,cAAc,IAAI,cAAc,IAAI,gBAAgB,IAAI,cAAc,IAAI;EAGtH,OADgB,KAAK,MAAM,kBAAkB,MAAM,IAAI,SACtC,SAAS,eAAe;CAC3C;CAEA,IAAI,SAAS,S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O,aAAa,QAAQ,YAAY,QAAQ,IAAI,KAAK,QAAQ,CAAC,CAAC,YAAY,IAAI,IAAI,KAAK,KAAK,CAAC,CAAC,YAAY;AACjH;AAEA,SAAS,wBAAwB,UAAqD;CACpF,MAAM,eAAe,eAAe,QAAQ;CAC5C,MAAM,QAAA,GAAO,0BAAA,gBAAA,CAAgB,cAAc,KAAK,IAAI,IAAI,CAAC;CACzD,OAAO,SAAS,OAAO,IAAI,KAAK,IAAI,CAAC,CAAC,YAAY,IAAI;AACxD;AAEA,SAAS,eAAe,UAAoD;CAC1E,IAAI,SAAS,SAAS,0BAAA,eAAe,UACnC,OAAO;EACL,MAAM,0BAAA,eAAe;EACrB,aAAa,KAAK,MAAM,SAAS,aAAa,aAAa;CAC7D;CAEF,OAAO;AACT"}
1
+ {"version":3,"file":"index.cjs","names":[],"sources":["../../src/scheduler/schedule-window.ts","../../src/scheduler/task-manager.ts","../../src/scheduler/adapter.ts"],"sourcesContent":["// One definition of \"when does this schedule fire\". The host expresses\n// intervals in milliseconds and the library (@receptron/task-scheduler) in\n// seconds, so every place that answers \"is it due now?\", \"when is the next\n// run?\" or \"which windows were missed?\" has to cross that boundary. Doing it\n// twice is what let the tick engine drift away from `nextWindowAfter`: its own\n// interval check counted from UTC midnight, so anything longer than a day\n// collapsed to \"every day at 00:00\" while the UI kept showing the real,\n// epoch-anchored next run (#2937).\n\nimport { SCHEDULE_TYPES, isDueAt, nextWindowAfter, parseTimeToMs, type TaskSchedule as LibrarySchedule } from \"@receptron/task-scheduler\";\n\nconst ONE_SECOND_MS = 1000;\nconst ONE_DAY_MS = 24 * 60 * 60 * ONE_SECOND_MS;\n\n/** A schedule as the host states it: intervals in milliseconds, or a daily\n * `HH:MM` UTC time. */\nexport type TaskSchedule = { type: typeof SCHEDULE_TYPES.interval; intervalMs: number } | { type: typeof SCHEDULE_TYPES.daily; time: string };\n\n/** An interval this engine can never turn into a window. Zero divides by zero\n * inside the library's `Math.ceil(afterMs / intervalMs)`; a negative or\n * non-finite one poisons the arithmetic with NaN, which compares false\n * everywhere and so hides itself. */\nfunction isUsableInterval(intervalMs: number): boolean {\n return Number.isFinite(intervalMs) && intervalMs > 0;\n}\n\n/** Milliseconds past UTC midnight for a daily `HH:MM`, or null when the string\n * does not name a time of day. Out-of-range values are rejected, not clamped\n * and not wrapped: `\"24:00\"` would otherwise land on the NEXT day's midnight\n * and `\"-1:00\"` on an hour before it, so a typo that used to be inert would\n * start firing — at 00:00 daily, or 61 times a day. */\nfunction dailyOffsetMs(time: string): number | null {\n const offsetMs = parseTimeToMs(time);\n return Number.isFinite(offsetMs) && offsetMs >= 0 && offsetMs < ONE_DAY_MS ? offsetMs : null;\n}\n\n/** Convert to the library's schedule shape. Milliseconds are divided, never\n * rounded: rounding a sub-second interval to `intervalSec: 0` is what made\n * `nextWindowAfter` answer NaN and `new Date(NaN).toISOString()` throw. */\nexport function toLibrarySchedule(schedule: TaskSchedule): LibrarySchedule {\n if (schedule.type === SCHEDULE_TYPES.interval) {\n return { type: SCHEDULE_TYPES.interval, intervalSec: schedule.intervalMs / ONE_SECOND_MS };\n }\n return { type: SCHEDULE_TYPES.daily, time: schedule.time };\n}\n\n/** True when a scheduled window falls inside the tick ending at `nowMs`.\n * Windows are anchored to the epoch, not to the current UTC day, so an\n * interval longer than 24h keeps its real period. */\nexport function isScheduleDueAt(schedule: TaskSchedule, nowMs: number, tickMs: number): boolean {\n if (unfireableScheduleReason(schedule) !== null) return false;\n return isDueAt(toLibrarySchedule(schedule), nowMs, tickMs);\n}\n\n/** The furthest instant `Date` can represent. A window past it is finite\n * arithmetic but not a date, and `toISOString()` answers that with a throw —\n * which, inside the state writer, silently loses the whole run record. */\nconst MAX_DATE_MS = 8.64e15;\n\n/** A window as an ISO timestamp, or null when the number is not a date. */\nexport function windowToIso(windowMs: number | null): string | null {\n if (windowMs === null || !Number.isFinite(windowMs) || Math.abs(windowMs) > MAX_DATE_MS) return null;\n return new Date(windowMs).toISOString();\n}\n\n/** The most recent window at or before `nowMs`, or null when the schedule has\n * none. `nextWindowAfter` only ever looks FORWARD, so asking it from\n * `nowMs - one period` answers the previous window whenever `nowMs` sits\n * exactly on a boundary, and a daily schedule read after its minute answers\n * TOMORROW. Both schedule kinds have a fixed period, so stepping one period\n * back off the next window is exact. */\nexport function latestWindowAtOrBefore(schedule: TaskSchedule, nowMs: number): number | null {\n if (unfireableScheduleReason(schedule) !== null) return null;\n const next = nextWindowAfter(toLibrarySchedule(schedule), nowMs);\n if (next === null || !Number.isFinite(next)) return null;\n if (next <= nowMs) return next;\n const periodMs = schedule.type === SCHEDULE_TYPES.interval ? schedule.intervalMs : ONE_DAY_MS;\n return next - periodMs;\n}\n\n/** Name the field that makes a schedule unfireable, or null when it is fine.\n * Returns the offending value (not a boolean) so the caller can put it in the\n * log — a task that silently never runs leaves no evidence to start from\n * (#2765). */\nexport function unfireableScheduleReason(schedule: TaskSchedule): { field: string; value: string } | null {\n if (schedule.type === SCHEDULE_TYPES.interval) {\n return isUsableInterval(schedule.intervalMs) ? null : { field: \"intervalMs\", value: String(schedule.intervalMs) };\n }\n return dailyOffsetMs(schedule.time) !== null ? null : { field: \"time\", value: schedule.time };\n}\n","// Generic dependency-ordered cron tick engine. Host-agnostic: the only\n// host coupling (a logger) is injected via options. Schedules are either\n// fixed intervals or a daily UTC time; tasks may declare a `dependsOn`\n// edge so an ordering like \"news fetch → journal → memory extraction\"\n// runs in sequence within one tick.\n\nimport type { MinimalLogger } from \"@mulmoclaude/common\";\nimport { isScheduleDueAt, unfireableScheduleReason, type TaskSchedule } from \"./schedule-window.js\";\n\nconst ONE_SECOND_MS = 1000;\nconst ONE_MINUTE_MS = 60 * ONE_SECOND_MS;\n\n// Gap between the START of each independently-due task within one tick. When\n// many tasks come due at the same minute (system journal + feed-refresh + a few\n// user tasks all at 20:00 UTC), firing every chat in the same event-loop turn\n// floods the machine; the mulmoclaude MCP broker each chat spawns then boots\n// under contention and can lose the startup race to the CLI's first tool call,\n// so that turn fails with `handlePermission not found` (#2057). Spacing the\n// launches by a second gives each broker room to connect. Far under one tick\n// (a handful of tasks spread over a few seconds), so nothing is delayed past\n// its window.\nconst DEFAULT_FIRING_STAGGER_MS = ONE_SECOND_MS;\n\n// The total stagger must stay well inside one tick, or the tail tasks start in a\n// LATER tick window and two ticks overlap. Cap all starts to this fraction of\n// `tickMs` regardless of task count or the configured gap — this keeps a debug\n// `tickMs === firingStaggerMs` (see server boot) from degenerating.\nconst MAX_STAGGER_FRACTION_OF_TICK = 0.5;\n\nconst realSleep = (delayMs: number): Promise<void> => new Promise((resolve) => setTimeout(resolve, delayMs));\n\n// Per-task stagger step: the configured gap, shrunk so the last of `count` tasks\n// still starts within MAX_STAGGER_FRACTION_OF_TICK of the tick. 0 disables it.\nfunction staggerStepMs(staggerMs: number, tickMs: number, count: number): number {\n if (staggerMs <= 0 || count <= 1) return 0;\n const maxStepMs = (tickMs * MAX_STAGGER_FRACTION_OF_TICK) / (count - 1);\n return Math.min(staggerMs, maxStepMs);\n}\n\n/** Minimal logger the engine logs through. Absent one, runs silent. */\nexport type SchedulerLogger = MinimalLogger;\n\nconst NOOP_LOG: SchedulerLogger = { info: () => {}, warn: () => {}, error: () => {} };\n\n// Re-exported, not redefined: the schedule shape belongs with the window\n// arithmetic that interprets it, and hosts have always imported it from here.\nexport type { TaskSchedule } from \"./schedule-window.js\";\n\nexport interface TaskRunContext {\n taskId: string;\n now: Date;\n}\n\nexport interface TaskDefinition {\n id: string;\n description?: string;\n schedule: TaskSchedule;\n enabled?: boolean; // default: true\n /** If set, this task only fires after the named task has completed\n * successfully in the current tick cycle. Enforces ordering like\n * \"news fetch → journal → memory extraction\". */\n dependsOn?: string;\n run: (ctx: TaskRunContext) => Promise<void>;\n}\n\nexport interface TaskSummary {\n id: string;\n description?: string | undefined;\n schedule: TaskSchedule;\n dependsOn?: string | undefined;\n}\n\nexport interface ITaskManager {\n registerTask: (def: TaskDefinition) => void;\n removeTask: (taskId: string) => void;\n /** Update the schedule of an existing task. Returns false if not found. */\n updateSchedule: (taskId: string, schedule: TaskSchedule) => boolean;\n start: () => void;\n stop: () => void;\n /** Run one tick manually (for testing). */\n tick: () => Promise<void>;\n listTasks: () => TaskSummary[];\n}\n\nexport interface TaskManagerOptions {\n tickMs?: number; // default: ONE_MINUTE_MS\n now?: () => Date; // default: () => new Date()\n log?: SchedulerLogger; // default: noop\n /** Gap between the start of each independently-due task in a tick (#2057).\n * Default DEFAULT_FIRING_STAGGER_MS; 0 fires them all at once. */\n firingStaggerMs?: number;\n /** Injected so tests advance time without real timers. Default setTimeout. */\n sleep?: (delayMs: number) => Promise<void>;\n}\n\nfunction isDue(now: Date, schedule: TaskSchedule, tickMs: number): boolean {\n return isScheduleDueAt(schedule, now.getTime(), tickMs);\n}\n\n/** Say out loud that this schedule can never fire. The task is still accepted —\n * `isDue` answers false forever, which is the safe outcome — but silence here\n * is what made \"the task I scheduled has never run once\" a bug with no\n * evidence anywhere to start from (#2765). Deliberately not a throw: a\n * consumer whose task has been quietly dead would get a boot crash instead. */\nfunction reportUnfireable(log: SchedulerLogger, taskId: string, schedule: TaskSchedule): void {\n const reason = unfireableScheduleReason(schedule);\n if (reason === null) return;\n log.error(`schedule has an unusable ${reason.field} — this task will never run`, { id: taskId, [reason.field]: reason.value });\n}\n\n/** Split the due tasks into those that may run immediately and those gated\n * behind a `dependsOn` edge (resolved later in the same tick cycle). */\nexport function collectDueTasks(\n currentTime: Date,\n registry: Map<string, TaskDefinition>,\n tickMs: number,\n): { independent: TaskDefinition[]; dependent: TaskDefinition[] } {\n const independent: TaskDefinition[] = [];\n const dependent: TaskDefinition[] = [];\n for (const def of registry.values()) {\n if (def.enabled === false) continue;\n if (!isDue(currentTime, def.schedule, tickMs)) continue;\n if (def.dependsOn) {\n dependent.push(def);\n } else {\n independent.push(def);\n }\n }\n return { independent, dependent };\n}\n\nasync function runAndTrack(def: TaskDefinition, currentTime: Date, succeeded: Set<string>, log: SchedulerLogger): Promise<void> {\n try {\n await def.run({ taskId: def.id, now: currentTime });\n succeeded.add(def.id);\n } catch (err) {\n log.error(\"task failed\", {\n id: def.id,\n error: String(err),\n });\n }\n}\n\nasync function runDependentChain(dependent: TaskDefinition[], currentTime: Date, succeeded: Set<string>, log: SchedulerLogger): Promise<void> {\n let remaining = [...dependent];\n let progress = true;\n while (remaining.length > 0 && progress) {\n progress = false;\n const next: TaskDefinition[] = [];\n for (const def of remaining) {\n const dep = def.dependsOn;\n if (!dep || !succeeded.has(dep)) {\n next.push(def);\n continue;\n }\n await runAndTrack(def, currentTime, succeeded, log);\n progress = true;\n }\n remaining = next;\n }\n}\n\ninterface TickConfig {\n tickMs: number;\n staggerMs: number;\n sleep: (delayMs: number) => Promise<void>;\n log: SchedulerLogger;\n}\n\nasync function runTick(now: () => Date, registry: Map<string, TaskDefinition>, cfg: TickConfig): Promise<void> {\n const currentTime = now();\n const { independent, dependent } = collectDueTasks(currentTime, registry, cfg.tickMs);\n\n // Per-invocation set — success does not leak across tick() calls.\n const succeeded = new Set<string>();\n\n // Staggered start (#2057), still concurrent: each fires after its own capped\n // delay but the tick awaits them all, preserving the previous \"all due tasks\n // ran this tick\" contract.\n const stepMs = staggerStepMs(cfg.staggerMs, cfg.tickMs, independent.length);\n await Promise.all(\n independent.map(async (def, index) => {\n if (stepMs > 0 && index > 0) await cfg.sleep(index * stepMs);\n await runAndTrack(def, currentTime, succeeded, cfg.log);\n }),\n );\n\n await runDependentChain(dependent, currentTime, succeeded, cfg.log);\n}\n\nexport function listTaskSummaries(registry: Map<string, TaskDefinition>): TaskSummary[] {\n return [...registry.values()].map((taskDef) => ({\n id: taskDef.id,\n description: taskDef.description,\n schedule: taskDef.schedule,\n dependsOn: taskDef.dependsOn,\n }));\n}\n\n// A tick runner that skips re-entry: if the previous tick is still draining its\n// staggered starts, drop this one so a slow tick + short tickMs can never run\n// two ticks concurrently.\nfunction makeGuardedTick(now: () => Date, registry: Map<string, TaskDefinition>, cfg: TickConfig): () => Promise<void> {\n let ticking = false;\n return async () => {\n if (ticking) return;\n ticking = true;\n try {\n await runTick(now, registry, cfg);\n } finally {\n ticking = false;\n }\n };\n}\n\nfunction resolveTickConfig(options?: TaskManagerOptions): { tickMs: number; now: () => Date; cfg: TickConfig } {\n const tickMs = options?.tickMs ?? ONE_MINUTE_MS;\n return {\n tickMs,\n now: options?.now ?? (() => new Date()),\n cfg: {\n tickMs,\n staggerMs: options?.firingStaggerMs ?? DEFAULT_FIRING_STAGGER_MS,\n sleep: options?.sleep ?? realSleep,\n log: options?.log ?? NOOP_LOG,\n },\n };\n}\n\nexport function createTaskManager(options?: TaskManagerOptions): ITaskManager {\n const { tickMs, now, cfg } = resolveTickConfig(options);\n const { log } = cfg;\n const registry = new Map<string, TaskDefinition>();\n let timer: ReturnType<typeof setInterval> | null = null;\n const onTick = makeGuardedTick(now, registry, cfg);\n\n return {\n async tick() {\n await onTick();\n },\n\n registerTask(def: TaskDefinition) {\n if (registry.has(def.id)) {\n throw new Error(`[task-manager] Task \"${def.id}\" is already registered`);\n }\n reportUnfireable(log, def.id, def.schedule);\n registry.set(def.id, def);\n log.info(\"registered\", { id: def.id });\n },\n\n updateSchedule(taskId: string, schedule: TaskSchedule): boolean {\n const def = registry.get(taskId);\n if (!def) return false;\n // Checked here as well as at registration: an override applied at run\n // time (`applyScheduleOverride`) never passes through `registerTask`.\n reportUnfireable(log, taskId, schedule);\n def.schedule = schedule;\n log.info(\"schedule updated\", { id: taskId });\n return true;\n },\n\n removeTask(taskId: string) {\n if (registry.delete(taskId)) {\n log.info(\"removed\", { id: taskId });\n }\n },\n\n start() {\n if (timer) return;\n // `onTick` guards re-entry but not failure — it has a `finally`, no\n // `catch` — so handing it straight to setInterval let a rejected tick\n // escape as an unhandled rejection, which the host turns into a process\n // exit. The scheduler must outlive one bad tick.\n timer = setInterval(() => {\n onTick().catch((err: unknown) => log.error(\"tick failed\", { error: String(err) }));\n }, tickMs);\n log.info(\"started\", { tickMs });\n },\n\n stop() {\n if (timer) {\n clearInterval(timer);\n timer = null;\n log.info(\"stopped\");\n }\n },\n\n listTasks() {\n return listTaskSummaries(registry);\n },\n };\n}\n","// Adapter that wires the pure scheduler library (@receptron/task-scheduler)\n// to a host's task-manager + workspace. Registers system tasks, runs\n// catch-up on startup, and persists execution state + logs.\n//\n// Host-agnostic: the workspace root, the atomic file writer, and the\n// logger are injected via `configureScheduler`. The host supplies its OWN\n// system tasks (journal / feeds / user-cron in MulmoClaude) to\n// `initScheduler` — the package owns no task definitions. Deliberately\n// thin: all complex scheduling logic lives in @receptron/task-scheduler.\n\nimport { existsSync } from \"node:fs\";\nimport { readFile, appendFile, mkdir } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport {\n type TaskExecutionState,\n type TaskLogEntry,\n type CatchUpTask,\n type TaskTrigger,\n emptyState,\n computeCatchUpPlan,\n nextWindowAfter,\n loadState,\n updateAndSave,\n appendLogEntry,\n queryLog,\n TASK_RESULTS,\n TASK_TRIGGERS,\n type MISSED_RUN_POLICIES,\n type StateMap,\n type StateDeps,\n type LogDeps,\n} from \"@receptron/task-scheduler\";\nimport type { ITaskManager, TaskDefinition, SchedulerLogger } from \"./task-manager.js\";\nimport { latestWindowAtOrBefore, toLibrarySchedule, unfireableScheduleReason, windowToIso } from \"./schedule-window.js\";\nimport { errorMessage } from \"../utils/errors.js\";\n\nconst SCHEDULER_CONFIG_DIR = \"config/scheduler\";\nconst SCHEDULER_DATA_DIR = \"data/scheduler/logs\";\n\n// ── Host injection ────────────────────────────────────────────────\n\nexport interface SchedulerConfig {\n /** Absolute workspace root — state.json + logs hang off it. */\n workspaceRoot: string;\n /** Host atomic file writer (used with `uniqueTmp` for the state file). */\n writeFileAtomic: (filePath: string, content: string, opts: { uniqueTmp: boolean }) => Promise<void>;\n /** Optional logger. */\n log?: SchedulerLogger;\n}\n\nconst NOOP_LOG: SchedulerLogger = { info: () => {}, warn: () => {}, error: () => {} };\n\nlet config: SchedulerConfig | null = null;\n\n/** Wire the adapter to a host. Call once at startup, before `initScheduler`. */\nexport function configureScheduler(injected: SchedulerConfig): void {\n config = injected;\n}\n\nfunction requireConfig(): SchedulerConfig {\n if (!config) throw new Error(\"scheduler: configureScheduler() not called\");\n return config;\n}\n\nfunction logger(): SchedulerLogger {\n return config?.log ?? NOOP_LOG;\n}\n\n// ── Paths ─────────────────────────────────────────────────────────\n\nfunction stateFilePath(): string {\n return path.join(requireConfig().workspaceRoot, SCHEDULER_CONFIG_DIR, \"state.json\");\n}\n\nfunction logsDir(): string {\n return path.join(requireConfig().workspaceRoot, SCHEDULER_DATA_DIR);\n}\n\n// ── I/O deps (real filesystem) ────────────────────────────────────\n\nfunction stateDeps(): StateDeps {\n return {\n readFile: (filePath: string) => readFile(filePath, \"utf-8\"),\n writeFileAtomic: (filePath: string, content: string) => requireConfig().writeFileAtomic(filePath, content, { uniqueTmp: true }),\n exists: existsSync,\n };\n}\n\nconst logDeps: LogDeps = {\n appendFile: (filePath: string, content: string) => appendFile(filePath, content),\n readFile: (filePath: string) => readFile(filePath, \"utf-8\"),\n exists: existsSync,\n ensureDir: (directoryPath: string) => mkdir(directoryPath, { recursive: true }).then(() => {}),\n};\n\n// ── System task registry ──────────────────────────────────────────\n\nexport interface SystemTaskDef {\n id: string;\n name: string;\n description: string;\n schedule: TaskDefinition[\"schedule\"];\n missedRunPolicy: typeof MISSED_RUN_POLICIES.skip | typeof MISSED_RUN_POLICIES.runOnce | typeof MISSED_RUN_POLICIES.runAll;\n run: () => Promise<void>;\n}\n\n// ── Public API ────────────────────────────────────────────────────\n\nlet stateMap: StateMap = new Map();\nconst systemTasks: SystemTaskDef[] = [];\nlet taskManagerRef: ITaskManager | null = null;\n\n/**\n * Initialize the scheduler adapter. Call once at server startup AFTER the\n * task-manager is created but BEFORE `taskManager.start()`.\n */\nexport async function initScheduler(taskManager: ITaskManager, tasks: SystemTaskDef[]): Promise<void> {\n await mkdir(path.dirname(stateFilePath()), { recursive: true });\n await mkdir(logsDir(), { recursive: true });\n\n stateMap = await loadState(stateFilePath(), stateDeps());\n systemTasks.length = 0;\n systemTasks.push(...tasks);\n taskManagerRef = taskManager;\n\n const plan = computeCatchUpPlan(catchUpTasksFor(tasks), stateMap, Date.now());\n\n for (const skip of plan.skipped) {\n logger().info(\"catch-up skipped\", { taskId: skip.taskId, windows: skip.windowCount });\n await safeUpdateState(skip.taskId, { lastRunAt: skip.lastWindow });\n }\n\n if (plan.runs.length > 0) {\n logger().info(\"catch-up enqueued\", { runs: plan.runs.length });\n for (const run of plan.runs) {\n const task = tasks.find((taskDef) => taskDef.id === run.taskId);\n if (!task) continue;\n await executeAndLog(task, run.context.scheduledFor, TASK_TRIGGERS.catchUp);\n }\n }\n\n // Register with task-manager for ongoing ticks\n for (const task of tasks) {\n taskManager.registerTask({\n id: task.id,\n description: task.description,\n schedule: task.schedule,\n run: async (ctx) => {\n const windowIso = computeCurrentWindow(task, ctx.now.getTime());\n await executeAndLog(task, windowIso, TASK_TRIGGERS.scheduled);\n },\n });\n }\n\n logger().info(\"initialized\", { tasks: tasks.map((taskDef) => taskDef.id), stateEntries: stateMap.size });\n}\n\n/** The catch-up input, with the tasks that can never fire left out. Their\n * windows come back NaN rather than null, which `listMissedWindows` cannot\n * see the end of — it fills to its cap and the first `new Date(NaN)` throws\n * `RangeError`, taking every other task's catch-up down with it at startup.\n * Registration still happens, so the task-manager reports the bad schedule. */\nfunction catchUpTasksFor(tasks: SystemTaskDef[]): CatchUpTask[] {\n return tasks\n .filter((taskDef) => {\n const reason = unfireableScheduleReason(taskDef.schedule);\n if (reason === null) return true;\n logger().error(`schedule has an unusable ${reason.field} — skipping catch-up, this task will never run`, {\n taskId: taskDef.id,\n [reason.field]: reason.value,\n });\n return false;\n })\n .map((taskDef) => ({\n id: taskDef.id,\n name: taskDef.name,\n schedule: toLibrarySchedule(taskDef.schedule),\n missedRunPolicy: taskDef.missedRunPolicy,\n enabled: true,\n }));\n}\n\n/** Apply a schedule override to a running system task. Updates the\n * in-memory task definition, the task-manager, and recalculates\n * nextScheduledAt in persisted state. */\nexport async function applyScheduleOverride(taskId: string, schedule: SystemTaskDef[\"schedule\"]): Promise<boolean> {\n const task = systemTasks.find((taskDef) => taskDef.id === taskId);\n if (!task || !taskManagerRef) return false;\n if (!taskManagerRef.updateSchedule(taskId, schedule)) return false;\n task.schedule = schedule;\n\n // Recalculate next window so the UI reflects the new schedule\n const nextScheduledAt = computeNextScheduledFor(task.schedule);\n await safeUpdateState(taskId, { nextScheduledAt });\n\n return true;\n}\n\n/** Query execution logs — used by API routes. */\nexport async function getSchedulerLogs(opts: { since?: string | undefined; taskId?: string | undefined; limit?: number | undefined }): Promise<TaskLogEntry[]> {\n return queryLog(logsDir(), opts, logDeps);\n}\n\n/** Get all task states — used by API routes. */\nexport function getSchedulerTasks(): {\n id: string;\n name: string;\n description: string;\n schedule: TaskDefinition[\"schedule\"];\n missedRunPolicy: string;\n state: TaskExecutionState;\n}[] {\n return systemTasks.map((taskDef) => ({\n id: taskDef.id,\n name: taskDef.name,\n description: taskDef.description,\n schedule: taskDef.schedule,\n missedRunPolicy: taskDef.missedRunPolicy,\n state: stateMap.get(taskDef.id) ?? emptyState(taskDef.id),\n }));\n}\n\n/** Read the persisted execution state for any task id (system, user, or\n * skill). Returns an empty state when the id has never run — used by the API\n * route to attach last-run / next-run / history state to user + skill tasks\n * it lists from other sources. */\nexport function getSchedulerTaskState(taskId: string): TaskExecutionState {\n return stateMap.get(taskId) ?? emptyState(taskId);\n}\n\n/** Record a run of an EXTERNAL (skill / user) task — one registered directly\n * on the task-manager rather than through `initScheduler`. Persists a log\n * entry + updates state so these tasks get the same history / last-run /\n * next-run as system tasks. Because they are fire-and-forget (`startChat`\n * spawns an async chat), `errorMessage` reflects whether the *dispatch*\n * succeeded, not the chat's eventual outcome; `chatSessionId` links the run\n * to the spawned session. */\nexport async function recordExternalRun(params: {\n id: string;\n name: string;\n schedule: TaskDefinition[\"schedule\"];\n scheduledFor: string;\n startedAt: string;\n durationMs: number;\n trigger: TaskTrigger;\n errorMessage: string | null;\n chatSessionId?: string | undefined;\n}): Promise<void> {\n await persistRun({\n meta: { id: params.id, name: params.name, schedule: params.schedule },\n scheduledFor: params.scheduledFor,\n startedAt: params.startedAt,\n durationMs: params.durationMs,\n trigger: params.trigger,\n errMsg: params.errorMessage,\n chatSessionId: params.chatSessionId,\n });\n}\n\n/** Test-only: clear config + in-memory state. */\nexport function resetSchedulerForTesting(): void {\n config = null;\n stateMap = new Map();\n systemTasks.length = 0;\n taskManagerRef = null;\n}\n\n// ── Internal ──────────────────────────────────────────────────────\n\nasync function executeAndLog(task: SystemTaskDef, scheduledFor: string, trigger: TaskTrigger): Promise<void> {\n const startedAt = new Date().toISOString();\n const startMs = Date.now();\n let errMsg: string | null = null;\n try {\n await task.run();\n } catch (err) {\n errMsg = errorMessage(err);\n logger().error(\"task failed\", { taskId: task.id, error: errMsg });\n }\n const durationMs = Date.now() - startMs;\n // Persistence is best-effort — never let disk failures propagate to the\n // tick loop or abort startup catch-up.\n await persistRun({ meta: { id: task.id, name: task.name, schedule: task.schedule }, scheduledFor, startedAt, durationMs, trigger, errMsg });\n}\n\n/** The minimum a run needs to persist state + a log entry — shared by system\n * tasks (`executeAndLog`) and external skill/user runs (`recordExternalRun`). */\ninterface TaskRunMeta {\n id: string;\n name: string;\n schedule: TaskDefinition[\"schedule\"];\n}\n\ninterface RunRecord {\n meta: TaskRunMeta;\n scheduledFor: string;\n startedAt: string;\n durationMs: number;\n trigger: TaskTrigger;\n errMsg: string | null;\n chatSessionId?: string | undefined;\n}\n\n/** Best-effort persistence — state and log are independent, so one failing\n * never blocks the other and neither propagates upward. */\nasync function persistRun(run: RunRecord): Promise<void> {\n await writeRunState(run);\n await writeRunLog(run);\n}\n\nasync function writeRunState(run: RunRecord): Promise<void> {\n const { meta, scheduledFor, durationMs, errMsg } = run;\n const isSuccess = errMsg === null;\n const currentState = stateMap.get(meta.id);\n try {\n await updateAndSave(\n stateFilePath(),\n stateMap,\n meta.id,\n {\n lastRunAt: scheduledFor,\n lastRunResult: isSuccess ? TASK_RESULTS.success : TASK_RESULTS.error,\n lastRunDurationMs: durationMs,\n lastErrorMessage: errMsg,\n consecutiveFailures: isSuccess ? 0 : (currentState?.consecutiveFailures ?? 0) + 1,\n totalRuns: (currentState?.totalRuns ?? 0) + 1,\n nextScheduledAt: computeNextScheduledFor(meta.schedule),\n },\n stateDeps(),\n );\n } catch (err) {\n logger().warn(\"state persistence failed\", { taskId: meta.id, error: String(err) });\n }\n}\n\nasync function writeRunLog(run: RunRecord): Promise<void> {\n const { meta, scheduledFor, startedAt, durationMs, trigger, errMsg, chatSessionId } = run;\n const isSuccess = errMsg === null;\n try {\n await appendLogEntry(\n logsDir(),\n {\n taskId: meta.id,\n taskName: meta.name,\n scheduledFor,\n startedAt,\n completedAt: new Date().toISOString(),\n result: isSuccess ? TASK_RESULTS.success : TASK_RESULTS.error,\n durationMs,\n trigger,\n ...(errMsg !== null && { errorMessage: errMsg }),\n ...(chatSessionId !== undefined && { chatSessionId }),\n },\n logDeps,\n );\n } catch (err) {\n logger().warn(\"log persistence failed\", { taskId: meta.id, error: String(err) });\n }\n}\n\n/** Safe state update — swallows errors. */\nasync function safeUpdateState(taskId: string, patch: Partial<TaskExecutionState>): Promise<void> {\n try {\n await updateAndSave(stateFilePath(), stateMap, taskId, patch, stateDeps());\n } catch (err) {\n logger().warn(\"state update failed\", { taskId, error: String(err) });\n }\n}\n\n/** Compute the window boundary that the current tick belongs to. For\n * scheduled runs, this is the epoch-aligned window — not the wall-clock\n * time of execution. This keeps lastRunAt consistent with catch-up's\n * window-based accounting. `tickMs` is the tick's own clock, not\n * `Date.now()`: the two drift apart by however long the tick took to reach\n * this task, and under an injected clock they are unrelated. */\nfunction computeCurrentWindow(task: SystemTaskDef, tickMs: number): string {\n return windowToIso(latestWindowAtOrBefore(task.schedule, tickMs)) ?? new Date(tickMs).toISOString();\n}\n\nfunction computeNextScheduledFor(schedule: TaskDefinition[\"schedule\"]): string | null {\n // The engine will never fire this one, so promising a next run in the UI\n // would be a lie — and the library still hands back a window for some of\n // them (`\"24:00\"` resolves to tomorrow's midnight).\n if (unfireableScheduleReason(schedule) !== null) return null;\n // `windowToIso` is what keeps a window that is not a date (NaN from a\n // degenerate schedule, or an interval so large the next window is past the\n // end of `Date`) from throwing here and taking the whole state write down.\n return windowToIso(nextWindowAfter(toLibrarySchedule(schedule), Date.now() + 1));\n}\n"],"mappings":";;;;;;;;;AAWA,IAAM,kBAAgB;AACtB,IAAM,aAAa,QAAe;;;;;AAUlC,SAAS,iBAAiB,YAA6B;CACrD,OAAO,OAAO,SAAS,UAAU,KAAK,aAAa;AACrD;;;;;;AAOA,SAAS,cAAc,MAA6B;CAClD,MAAM,YAAA,GAAW,0BAAA,cAAA,CAAc,IAAI;CACnC,OAAO,OAAO,SAAS,QAAQ,KAAK,YAAY,KAAK,WAAW,aAAa,WAAW;AAC1F;;;;AAKA,SAAgB,kBAAkB,UAAyC;CACzE,IAAI,SAAS,SAAS,0BAAA,eAAe,UACnC,OAAO;EAAE,MAAM,0BAAA,eAAe;EAAU,aAAa,SAAS,aAAa;CAAc;CAE3F,OAAO;EAAE,MAAM,0BAAA,eAAe;EAAO,MAAM,SAAS;CAAK;AAC3D;;;;AAKA,SAAgB,gBAAgB,UAAwB,OAAe,QAAyB;CAC9F,IAAI,yBAAyB,QAAQ,MAAM,MAAM,OAAO;CACxD,QAAA,GAAO,0BAAA,QAAA,CAAQ,kBAAkB,QAAQ,GAAG,OAAO,MAAM;AAC3D;;;;AAKA,IAAM,cAAc;;AAGpB,SAAgB,YAAY,UAAwC;CAClE,IAAI,aAAa,QAAQ,CAAC,OAAO,SAAS,QAAQ,KAAK,KAAK,IAAI,QAAQ,IAAI,aAAa,OAAO;CAChG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,YAAY;AACxC;;;;;;;AAQA,SAAgB,uBAAuB,UAAwB,OAA8B;CAC3F,IAAI,yBAAyB,QAAQ,MAAM,MAAM,OAAO;CACxD,MAAM,QAAA,GAAO,0BAAA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