watch-interval.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. /**
  2. * Watch / cron self-reminder interval helpers.
  3. *
  4. * Shared between the daemon (server-side resolution for /api/cron/self-reminder),
  5. * the CLI (mavis cron self), and the UI (/watch slash command). All three layers
  6. * accept the same surface so users get the same forgiveness.
  7. *
  8. * Accepted forms (case-insensitive):
  9. * - Natural-language duration: "30s" | "5m" | "2h" | "1d" | "1w"
  10. * - Compound duration: "1h30m" | "2d12h"
  11. * - Raw 5-field cron expression: "* / 5 * * * *" (passes through unchanged)
  12. *
  13. * The parser is intentionally minimal — it covers the common self-reminder
  14. * cases (seconds → days). Anything more exotic should be a raw cron expression.
  15. */
  16. const SECONDS_PER_UNIT: Record<string, number> = {
  17. s: 1,
  18. m: 60,
  19. h: 3600,
  20. d: 86400,
  21. w: 604800,
  22. };
  23. /** Maximum self-reminder TTL allowed by the daemon — 30 days. */
  24. export const MAX_SELF_REMINDER_TTL_SECONDS = 30 * 86400;
  25. /** Default self-reminder TTL when caller omits --ttl. */
  26. export const DEFAULT_SELF_REMINDER_TTL_SECONDS = 14 * 86400;
  27. /** Sentinel TTL meaning "never auto-expire". Caller is responsible for cleanup. */
  28. export const TTL_NEVER = 'never';
  29. export interface ParsedInterval {
  30. /** A valid 5-field cron expression usable by croner. */
  31. cronExpr: string;
  32. /** Approximate seconds between ticks (best-effort, only meaningful for duration input). */
  33. approxSeconds: number;
  34. /** Original user input, lowercased and trimmed. */
  35. raw: string;
  36. }
  37. /**
  38. * Parse a user-supplied interval string into a cron expression.
  39. *
  40. * @throws Error with a user-facing message when the input is unparseable.
  41. */
  42. export function parseWatchInterval(input: string): ParsedInterval {
  43. const raw = input.trim().toLowerCase();
  44. if (!raw) {
  45. throw new Error('Interval is empty. Try "5m", "30s", or a cron expression.');
  46. }
  47. // 5-field cron expressions contain whitespace; pass through after a sanity check.
  48. if (/\s/.test(raw)) {
  49. const parts = raw.split(/\s+/);
  50. if (parts.length < 5 || parts.length > 6) {
  51. throw new Error(
  52. `Cannot parse interval "${input}". ` +
  53. 'Expected a duration like "5m" or "1h30m", or a 5-field cron expression like "*/5 * * * *".',
  54. );
  55. }
  56. // We trust croner to reject syntactically wrong cron strings later.
  57. return { cronExpr: raw, approxSeconds: 0, raw };
  58. }
  59. // Compound duration: "1h30m", "2d12h", "30s", "1w" …
  60. const totalSeconds = parseDurationSeconds(raw, input);
  61. if (totalSeconds < 1) {
  62. throw new Error(`Interval must be at least 1 second; got "${input}".`);
  63. }
  64. return { cronExpr: secondsToCronExpr(totalSeconds, input), approxSeconds: totalSeconds, raw };
  65. }
  66. /** Convert a compound duration string into total seconds. */
  67. function parseDurationSeconds(raw: string, original: string): number {
  68. // Match all <number><unit> tuples; reject anything left over.
  69. const matches: RegExpExecArray[] = [];
  70. const re = /(\d+)([smhdw])/g;
  71. let m: RegExpExecArray | null;
  72. while ((m = re.exec(raw)) !== null) {
  73. matches.push(m);
  74. }
  75. if (matches.length === 0) {
  76. throw new Error(
  77. `Cannot parse interval "${original}". Use forms like "30s", "5m", "1h30m", or a cron expression.`,
  78. );
  79. }
  80. const consumed = matches.reduce((acc, mm) => acc + mm[0].length, 0);
  81. if (consumed !== raw.length) {
  82. throw new Error(
  83. `Cannot parse interval "${original}". Use forms like "30s", "5m", "1h30m", or a cron expression.`,
  84. );
  85. }
  86. let total = 0;
  87. for (const mm of matches) {
  88. const value = parseInt(mm[1]!, 10);
  89. const unit = mm[2]!;
  90. const factor = SECONDS_PER_UNIT[unit];
  91. if (!factor) {
  92. throw new Error(`Unknown duration unit "${unit}" in "${original}".`);
  93. }
  94. total += value * factor;
  95. }
  96. return total;
  97. }
  98. /**
  99. * Best-effort conversion of a fixed-period duration into a 5-field cron
  100. * expression that croner understands.
  101. *
  102. * The cron grammar cannot express arbitrary periods (e.g. "every 47 seconds")
  103. * with second-level precision, so we approximate to the nearest sensible
  104. * unit. The tradeoff is acceptable for self-reminders: the user typed "5m" and
  105. * tolerates the cron form (slash-5 stars) rather than running exactly every
  106. * 300 000 ms.
  107. */
  108. function secondsToCronExpr(seconds: number, original: string): string {
  109. // Sub-minute → use the 6-field form with seconds. croner supports "*/N * * * * *".
  110. if (seconds < 60) {
  111. return `*/${seconds} * * * * *`;
  112. }
  113. // Whole minutes
  114. if (seconds % 60 === 0 && seconds < 3600) {
  115. return `*/${seconds / 60} * * * *`;
  116. }
  117. // Whole hours
  118. if (seconds % 3600 === 0 && seconds < 86400) {
  119. const hours = seconds / 3600;
  120. return hours === 1 ? '0 * * * *' : `0 */${hours} * * *`;
  121. }
  122. // Whole days
  123. if (seconds % 86400 === 0) {
  124. const days = seconds / 86400;
  125. return days === 1 ? '0 0 * * *' : `0 0 */${days} * *`;
  126. }
  127. // Mixed: round down to the nearest whole minute.
  128. if (seconds < 3600) {
  129. const mins = Math.max(1, Math.floor(seconds / 60));
  130. return `*/${mins} * * * *`;
  131. }
  132. // For any longer mixed period (e.g. 1h30m), schedule on the hour every N hours,
  133. // rounded down. Better to fire slightly less often than to silently lose ticks.
  134. const hours = Math.max(1, Math.floor(seconds / 3600));
  135. if (hours >= 24) {
  136. const days = Math.max(1, Math.floor(hours / 24));
  137. return `0 0 */${days} * *`;
  138. }
  139. if (hours === 1) return '0 * * * *';
  140. return `0 */${hours} * * *`;
  141. }
  142. export interface ParsedTtl {
  143. /** Seconds until expiry. `null` means "never expires". */
  144. seconds: number | null;
  145. /** ISO-like local timestamp at which the reminder expires. `null` for never. */
  146. expiresAtMs: number | null;
  147. }
  148. /**
  149. * Parse a TTL string. Accepts the same duration grammar as {@link parseWatchInterval}
  150. * plus the literal `"never"`.
  151. *
  152. * Returns `null`-bearing fields for never; otherwise returns the absolute
  153. * expiry millis derived from `nowMs`.
  154. *
  155. * @throws Error if the TTL exceeds {@link MAX_SELF_REMINDER_TTL_SECONDS} or is malformed.
  156. */
  157. export function parseSelfReminderTtl(input: string | undefined, nowMs: number): ParsedTtl {
  158. const raw = (input ?? '').trim().toLowerCase();
  159. if (!raw) {
  160. return {
  161. seconds: DEFAULT_SELF_REMINDER_TTL_SECONDS,
  162. expiresAtMs: nowMs + DEFAULT_SELF_REMINDER_TTL_SECONDS * 1000,
  163. };
  164. }
  165. if (raw === TTL_NEVER) {
  166. return { seconds: null, expiresAtMs: null };
  167. }
  168. const seconds = parseDurationSeconds(raw, input ?? raw);
  169. if (seconds < 1) {
  170. throw new Error(`TTL must be at least 1 second; got "${input}".`);
  171. }
  172. if (seconds > MAX_SELF_REMINDER_TTL_SECONDS) {
  173. throw new Error(
  174. `TTL must not exceed 30 days (${MAX_SELF_REMINDER_TTL_SECONDS} seconds); got "${input}".`,
  175. );
  176. }
  177. return { seconds, expiresAtMs: nowMs + seconds * 1000 };
  178. }
  179. /**
  180. * Append a self-cleanup snippet to a self-reminder prompt.
  181. *
  182. * The snippet instructs the receiving session to delete itself if the wall
  183. * clock has passed `expiry.atMs`. We rely on prompt discipline rather than a
  184. * server-side TTL field so that older daemons (which lack a TTL column) still
  185. * behave correctly when the prompt fires.
  186. *
  187. * Pass `expiry === null` to suppress the snippet (used for `--ttl never`).
  188. *
  189. * The `expiry.label` field is the local-time string the receiving session
  190. * sees inside the prompt body. Callers must format it via
  191. * `formatLocalDateTime(expiry.atMs)` before passing — this helper does NOT
  192. * fall back to `toISOString()` because emitting UTC ISO strings into prompts
  193. * violates AGENTS.md §1's "render local time at the edge" rule.
  194. */
  195. export function appendTtlPromptSuffix(
  196. basePrompt: string,
  197. options: {
  198. /** When non-null, both ms and label are required (paired); null disables auto-expiry. */
  199. expiry: { atMs: number; label: string } | null;
  200. agentName: string;
  201. cronName: string;
  202. quietOnSkip: boolean;
  203. },
  204. ): string {
  205. const lines = [basePrompt.trimEnd()];
  206. if (options.expiry !== null) {
  207. lines.push(
  208. '',
  209. '---',
  210. `[self-reminder TTL] This reminder expires at ${options.expiry.label}.`,
  211. `If \`Date.now() > ${options.expiry.atMs}\`, your first action MUST be to delete this reminder and exit silently:`,
  212. `use the \`mavis\` tool — run \`cron list\` (agent_name: "${options.agentName}"), find the cron named "${options.cronName}", then run \`cron delete\` with its cron_id.`,
  213. );
  214. } else {
  215. lines.push(
  216. '',
  217. '---',
  218. '[self-reminder] No TTL — you are responsible for deleting this cron via the `mavis` tool (`cron list` → `cron delete`) when the reason is gone.',
  219. );
  220. }
  221. if (options.quietOnSkip) {
  222. lines.push(
  223. '',
  224. '[gate-discipline] If your guard condition is not met (CI still running, MR not merged, ' +
  225. 'no new evidence), wrap a one-line status in `<mavis-progress>...</mavis-progress>` ' +
  226. 'and exit. The progress tag lets the user glance at "still waiting" without ' +
  227. 'lighting up an unread notification. Do NOT send IMs and do NOT write plain replies ' +
  228. 'on skip ticks.',
  229. );
  230. }
  231. return lines.join('\n');
  232. }
  233. /**
  234. * Generate a short, human-friendly cron name when the caller did not supply one.
  235. *
  236. * Uses a 6-character hex token from a passed-in randomness source for testability.
  237. * The prefix doubles as a hint in the cron list ("watch-..." marks slash-created tasks).
  238. */
  239. export function generateWatchCronName(prefix: string, randomHex6: string): string {
  240. if (!/^[0-9a-f]{6}$/i.test(randomHex6)) {
  241. throw new Error('randomHex6 must be a 6-character hex string');
  242. }
  243. return `${prefix}-${randomHex6.toLowerCase()}`;
  244. }