@supa-media/tex-contract 0.0.0-stage → 0.2.7

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 (212) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +11 -2
  3. package/package.json +16 -4
  4. package/texContract/aboutLines.cjs +117 -0
  5. package/texContract/aboutLines.d.cts +14 -0
  6. package/texContract/aboutNoteLimits.cjs +41 -0
  7. package/texContract/aboutNoteLimits.d.cts +5 -0
  8. package/texContract/actionManual.cjs +104 -0
  9. package/texContract/activityHint.cjs +40 -0
  10. package/texContract/activityHint.d.cts +4 -0
  11. package/texContract/asks.cjs +16 -0
  12. package/texContract/asks.d.cts +6 -0
  13. package/texContract/asksToFile.cjs +20 -0
  14. package/texContract/asksToFile.d.cts +2 -0
  15. package/texContract/attention.cjs +138 -0
  16. package/texContract/attention.d.cts +20 -0
  17. package/texContract/browserHandback.cjs +13 -0
  18. package/texContract/browserHandback.d.cts +3 -0
  19. package/texContract/browserOwner.cjs +31 -0
  20. package/texContract/browserOwner.d.cts +2 -0
  21. package/texContract/bytes.cjs +12 -0
  22. package/texContract/chatHistoryPath.cjs +38 -0
  23. package/texContract/chatHistoryPath.d.cts +5 -0
  24. package/texContract/chatLedger.cjs +91 -0
  25. package/texContract/chatLedger.d.cts +21 -0
  26. package/texContract/computerTool.cjs +102 -0
  27. package/texContract/computerTool.d.cts +16 -0
  28. package/texContract/consentYes.cjs +22 -0
  29. package/texContract/consentYes.d.cts +5 -0
  30. package/texContract/contextGateway.cjs +52 -0
  31. package/texContract/contextGateway.d.cts +19 -0
  32. package/texContract/deskEligible.cjs +20 -0
  33. package/texContract/deskEligible.d.cts +3 -0
  34. package/texContract/downloads.cjs +129 -0
  35. package/texContract/downloads.d.cts +15 -0
  36. package/texContract/egressLedger.cjs +114 -0
  37. package/texContract/egressLedger.d.cts +14 -0
  38. package/texContract/emailRead.cjs +38 -0
  39. package/texContract/emailRead.d.cts +5 -0
  40. package/texContract/eventWords.cjs +35 -0
  41. package/texContract/eventWords.d.cts +4 -0
  42. package/texContract/fileParts.cjs +43 -0
  43. package/texContract/fileParts.d.cts +6 -0
  44. package/texContract/fileTables.cjs +243 -0
  45. package/texContract/fileWords.cjs +169 -0
  46. package/texContract/folded.cjs +16 -0
  47. package/texContract/folded.d.cts +3 -0
  48. package/texContract/googleAiAccess.cjs +12 -0
  49. package/texContract/googleAiAccess.d.cts +2 -0
  50. package/texContract/graphWires.cjs +18 -0
  51. package/texContract/graphWires.d.cts +5 -0
  52. package/texContract/groupSession.cjs +28 -0
  53. package/texContract/groupSession.d.cts +7 -0
  54. package/texContract/guestNames.cjs +136 -0
  55. package/texContract/guestNames.d.cts +35 -0
  56. package/texContract/heard.cjs +19 -0
  57. package/texContract/heard.d.cts +4 -0
  58. package/texContract/heldOffer.cjs +57 -0
  59. package/texContract/heldOffer.d.cts +8 -0
  60. package/texContract/helperCallers.cjs +29 -0
  61. package/texContract/helperCallers.d.cts +4 -0
  62. package/texContract/identity.cjs +179 -0
  63. package/texContract/identity.d.cts +8 -0
  64. package/texContract/jobLogEntries.cjs +93 -0
  65. package/texContract/jobLogEntries.d.cts +12 -0
  66. package/texContract/judgedActions.cjs +20 -0
  67. package/texContract/judgedActions.d.cts +4 -0
  68. package/texContract/labSandboxGate.cjs +63 -0
  69. package/texContract/labSandboxGate.d.cts +9 -0
  70. package/texContract/ledgerReadChars.cjs +4 -0
  71. package/texContract/ledgerReadChars.d.cts +3 -0
  72. package/texContract/mailCheck.cjs +90 -0
  73. package/texContract/mailCheck.d.cts +12 -0
  74. package/texContract/mailEntries.cjs +64 -0
  75. package/texContract/mailEntries.d.cts +13 -0
  76. package/texContract/mailHealth.cjs +60 -0
  77. package/texContract/mailHealth.d.cts +10 -0
  78. package/texContract/notePath.cjs +99 -0
  79. package/texContract/notePath.d.cts +4 -0
  80. package/texContract/noteRunFacts.cjs +136 -0
  81. package/texContract/noteRunFacts.d.cts +32 -0
  82. package/texContract/objectEtag.cjs +84 -0
  83. package/texContract/objectEtag.d.cts +4 -0
  84. package/texContract/objectPlace.cjs +32 -0
  85. package/texContract/objectPlace.d.cts +5 -0
  86. package/texContract/pageJobs.cjs +226 -0
  87. package/texContract/pageJobs.d.cts +13 -0
  88. package/texContract/pdfLinks.cjs +135 -0
  89. package/texContract/pdfLinks.d.cts +4 -0
  90. package/texContract/personHub.cjs +38 -0
  91. package/texContract/personHub.d.cts +5 -0
  92. package/texContract/personNameText.cjs +18 -0
  93. package/texContract/personNameText.d.cts +3 -0
  94. package/texContract/pinnedContext.cjs +12 -0
  95. package/texContract/pinnedContext.d.cts +3 -0
  96. package/texContract/quietHoursWindow.cjs +36 -0
  97. package/texContract/quietHoursWindow.d.cts +3 -0
  98. package/texContract/scopeClamp.cjs +117 -0
  99. package/texContract/scopeClamp.d.cts +5 -0
  100. package/texContract/scopes.cjs +29 -0
  101. package/texContract/scopes.d.cts +7 -0
  102. package/texContract/searchSettings.cjs +54 -0
  103. package/texContract/searchSettings.d.cts +6 -0
  104. package/texContract/settingHabits.cjs +87 -0
  105. package/texContract/settingHabits.d.cts +20 -0
  106. package/texContract/settingsNotes.cjs +217 -0
  107. package/texContract/settingsNotes.d.cts +26 -0
  108. package/texContract/shownEmail.cjs +181 -0
  109. package/texContract/texClients.cjs +53 -0
  110. package/texContract/texClients.d.cts +12 -0
  111. package/texContract/texGraph.cjs +593 -0
  112. package/texContract/texGraph.d.cts +55 -0
  113. package/texContract/texKeys.cjs +100 -0
  114. package/texContract/texKeys.d.cts +13 -0
  115. package/texContract/texOwnSources.cjs +9 -0
  116. package/texContract/texOwnSources.d.cts +3 -0
  117. package/texContract/texStoreNames.cjs +26 -0
  118. package/texContract/texStoreNames.d.cts +12 -0
  119. package/texContract/texStoreWire.cjs +306 -0
  120. package/texContract/texStoreWire.d.cts +32 -0
  121. package/texContract/threadsFold.cjs +75 -0
  122. package/texContract/threadsFold.d.cts +22 -0
  123. package/texContract/toolActions.cjs +253 -0
  124. package/texContract/toolCatalog.cjs +49 -0
  125. package/texContract/toolCatalog.generated.json +90 -0
  126. package/texContract/toolContract.cjs +52 -0
  127. package/texContract/toolContract.d.cts +12 -0
  128. package/texContract/toolShapes.cjs +14 -0
  129. package/texContract/transcription.cjs +101 -0
  130. package/texContract/transcription.d.cts +3 -0
  131. package/texContract/treeJobs.cjs +31 -0
  132. package/texContract/treeJobs.d.cts +3 -0
  133. package/texContract/turnSession.cjs +90 -0
  134. package/texContract/turnSession.d.cts +19 -0
  135. package/texContract/turnWords.cjs +90 -0
  136. package/texContract/turnWords.d.cts +9 -0
  137. package/texContract/uploadImages.cjs +131 -0
  138. package/texContract/uploadImages.d.cts +13 -0
  139. package/texContract/v2Names.cjs +41 -0
  140. package/texContract/v2SearchFetch.cjs +316 -0
  141. package/texContract/v2Translate.cjs +123 -0
  142. package/texContract/vaultTools.cjs +112 -0
  143. package/texContract/vaultTools.d.cts +15 -0
  144. package/texContract/yesWords.cjs +91 -0
  145. package/texShared/argumentCoercion.cjs +93 -0
  146. package/texShared/cellComments.cjs +122 -0
  147. package/texShared/cellComments.d.cts +21 -0
  148. package/texShared/comments.cjs +586 -0
  149. package/texShared/comments.d.cts +115 -0
  150. package/texShared/contentTypes.cjs +85 -0
  151. package/texShared/fileKinds.cjs +123 -0
  152. package/texShared/flags.cjs +124 -0
  153. package/texShared/flags.d.cts +21 -0
  154. package/texShared/folderJobInfo.cjs +301 -0
  155. package/texShared/folderJobInfo.d.cts +40 -0
  156. package/texShared/folderRoles.cjs +512 -0
  157. package/texShared/folderRoles.d.cts +73 -0
  158. package/texShared/githubOidc.ts +98 -0
  159. package/texShared/groupRunQuestions.cjs +98 -0
  160. package/texShared/groupRunQuestions.d.cts +4 -0
  161. package/texShared/inboxFolders.cjs +49 -0
  162. package/texShared/inboxFolders.d.cts +5 -0
  163. package/texShared/ink/drawing.cjs +474 -0
  164. package/texShared/ink/texFigure.cjs +252 -0
  165. package/texShared/ink/texFigure.d.cts +36 -0
  166. package/texShared/ink/texPoses.cjs +180 -0
  167. package/texShared/ink/texPoses.d.cts +20 -0
  168. package/texShared/jobPartEnd.cjs +133 -0
  169. package/texShared/jobPartEnd.d.cts +13 -0
  170. package/texShared/jobResume.cjs +31 -0
  171. package/texShared/jobResume.d.cts +5 -0
  172. package/texShared/jobSplit.cjs +90 -0
  173. package/texShared/jobSplit.d.cts +6 -0
  174. package/texShared/jobStart.cjs +56 -0
  175. package/texShared/jobStart.d.cts +9 -0
  176. package/texShared/mail.cjs +400 -0
  177. package/texShared/mail.d.cts +56 -0
  178. package/texShared/messageAnchors.cjs +38 -0
  179. package/texShared/models/aiKeys.cjs +137 -0
  180. package/texShared/models/aiKeys.d.cts +42 -0
  181. package/texShared/models/aiKeys.json +56 -0
  182. package/texShared/models/creditRest.cjs +269 -0
  183. package/texShared/models/promptBudget.cjs +295 -0
  184. package/texShared/models/promptSections.cjs +29 -0
  185. package/texShared/noteAppLink.cjs +23 -0
  186. package/texShared/notePreview.cjs +219 -0
  187. package/texShared/notePreview.d.cts +21 -0
  188. package/texShared/pages/blocks.cjs +215 -0
  189. package/texShared/pages/cover.cjs +164 -0
  190. package/texShared/pages/css.cjs +181 -0
  191. package/texShared/pages/cssBlocks.cjs +264 -0
  192. package/texShared/pages/draw.cjs +212 -0
  193. package/texShared/pages/drawRich.cjs +232 -0
  194. package/texShared/pages/html.cjs +168 -0
  195. package/texShared/pages/inline.cjs +251 -0
  196. package/texShared/pages/layout.cjs +76 -0
  197. package/texShared/pages/parse.cjs +418 -0
  198. package/texShared/pages/render.cjs +200 -0
  199. package/texShared/pages/skill.cjs +147 -0
  200. package/texShared/pages/skill.d.cts +5 -0
  201. package/texShared/pages/templates.cjs +336 -0
  202. package/texShared/r2Store.cjs +163 -0
  203. package/texShared/remoteImage.cjs +177 -0
  204. package/texShared/routines.cjs +656 -0
  205. package/texShared/routines.d.cts +86 -0
  206. package/texShared/servedListing.cjs +250 -0
  207. package/texShared/servedListing.d.cts +17 -0
  208. package/texShared/sheetCsv.cjs +566 -0
  209. package/texShared/sheetCsv.d.cts +91 -0
  210. package/texShared/storageLayout.cjs +88 -0
  211. package/texShared/storeKeys.cjs +144 -0
  212. package/texShared/toolArguments.cjs +323 -0
@@ -0,0 +1,656 @@
1
+ /**
2
+ * Routines: notes that run on a schedule.
3
+ *
4
+ * A routine is one Markdown note at `tex/routines/<how-often>/<name>.md`, or
5
+ * at `routines/<how-often>/<name>.md`, where routines lived before Tex had a
6
+ * folder of its own (the owner, 2026-10-14: both run, nothing is moved). The
7
+ * folder says how often it runs, the body says what to do in plain words, and a
8
+ * few optional front matter lines fine-tune it. Adding the file starts it,
9
+ * deleting it stops it, and moving it to another folder changes how often it
10
+ * runs. Decided by the owner, 2026-10-07; see `docs/decisions/routines.md`.
11
+ *
12
+ * This file is the one reading of that format. The gateway, the control plane
13
+ * and the app all import it, so "when does this run" has one answer. It is
14
+ * CommonJS for the same reason as `storageLayout.cjs`: the gateway is plain
15
+ * JavaScript and cannot import this package's TypeScript.
16
+ *
17
+ * Nothing here reads a clock or a bucket. Every function takes what it needs.
18
+ */
19
+
20
+ /** Where routines lived first. Still read, and its notes run exactly as before. */
21
+ const ROUTINES_FOLDER = "routines/";
22
+
23
+ /** Where new routines and reminders go: Tex's own folder (the owner, 2026-10-14). */
24
+ const TEX_ROUTINES_FOLDER = "tex/routines/";
25
+
26
+ /**
27
+ * Every routine root, the new one first. Neither is a prefix of the other, so
28
+ * a path is under at most one of them.
29
+ */
30
+ const ROUTINE_ROOTS = Object.freeze([TEX_ROUTINES_FOLDER, ROUTINES_FOLDER]);
31
+
32
+ /** The fastest a routine may run. Anything faster is refused, not rounded. */
33
+ const MIN_INTERVAL_MINUTES = 5;
34
+
35
+ /** Where a run's history is kept: Context's own space in the person's bucket. */
36
+ const ROUTINE_RUNS_PREFIX = ".context/agent/routines/";
37
+
38
+ /**
39
+ * Each root's run-history prefix. The old root's is the key it always had,
40
+ * byte for byte (a stable on-bucket format); the new root's is its own, so
41
+ * `routines/daily/x.md` and `tex/routines/daily/x.md` never share a history.
42
+ */
43
+ const ROUTINE_RUNS_PREFIXES = Object.freeze({
44
+ [ROUTINES_FOLDER]: ROUTINE_RUNS_PREFIX,
45
+ [TEX_ROUTINES_FOLDER]: ".context/agent/tex/routines/",
46
+ });
47
+
48
+ /** The routine root `path` starts with (`"tex/routines/"` or `"routines/"`), or null. */
49
+ function routineRootOf(path) {
50
+ if (typeof path !== "string") return null;
51
+ const lower = path.toLowerCase();
52
+ for (const root of ROUTINE_ROOTS) {
53
+ if (lower.slice(0, root.length) === root) return root;
54
+ }
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * Whether a change at `path` can change which routines exist: a routine root,
60
+ * anything under one (scheduled or not), or a folder a root sits in (`tex`,
61
+ * whose move or deletion takes `tex/routines/` with it). What a write is
62
+ * reported for, and what makes the control plane re-read the roots. A note
63
+ * beside the root, like `tex/about.md`, is not one.
64
+ */
65
+ function isRoutinePath(path) {
66
+ if (typeof path !== "string") return false;
67
+ const normalized = path.replace(/^\/+|\/+$/g, "").toLowerCase();
68
+ if (normalized === "") return false;
69
+ return ROUTINE_ROOTS.some((root) => normalized.startsWith(root) || root.startsWith(`${normalized}/`));
70
+ }
71
+
72
+ /**
73
+ * A group chat's routines live in its home, `tex/groups/<words>/routines/`, as a person's live in `tex/routines/`
74
+ * (the owner, 2026-11-02; `docs/decisions/texting-assistant/chat-routines.md`). `{ words, routinePath }` for a path
75
+ * at or under a home's routines folder, `routinePath` the same path under `tex/routines/` so every rule a routine's
76
+ * path carries reads it as one; null for anything else.
77
+ */
78
+ const HOME_ROUTINES = /^tex\/groups\/([a-z][a-z0-9-]{0,62})\/routines(?:\/(.*))?$/;
79
+
80
+ function homeRoutineOf(path) {
81
+ if (typeof path !== "string") return null;
82
+ const match = HOME_ROUTINES.exec(path.replace(/^\/+|\/+$/g, "").toLowerCase());
83
+ if (!match) return null;
84
+ return { words: match[1], routinePath: match[2] === undefined ? TEX_ROUTINES_FOLDER.slice(0, -1) : `${TEX_ROUTINES_FOLDER}${match[2]}` };
85
+ }
86
+
87
+ /** Whether a change at `path` can change a chat's routines: its home's routines folder or anything under it. */
88
+ function isHomeRoutinePath(path) {
89
+ return homeRoutineOf(path) !== null;
90
+ }
91
+
92
+ /** When a daily-or-slower routine runs if its file names no time. */
93
+ const DEFAULT_AT = Object.freeze({ hour: 8, minute: 0 });
94
+
95
+ const UNITS = Object.freeze(["minute", "hour", "day", "week", "month", "once"]);
96
+
97
+ const NAMED_FOLDERS = Object.freeze({
98
+ hourly: { unit: "hour", every: 1 },
99
+ daily: { unit: "day", every: 1 },
100
+ weekly: { unit: "week", every: 1 },
101
+ biweekly: { unit: "week", every: 2 },
102
+ "bi-weekly": { unit: "week", every: 2 },
103
+ fortnightly: { unit: "week", every: 2 },
104
+ monthly: { unit: "month", every: 1 },
105
+ quarterly: { unit: "month", every: 3 },
106
+ yearly: { unit: "month", every: 12 },
107
+ // A reminder: runs once, at the date and time its file names, then marks
108
+ // itself `done:` (the owner, 2026-10-14).
109
+ once: { unit: "once", every: 1 },
110
+ });
111
+
112
+ const WEEKDAYS = Object.freeze(["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"]);
113
+
114
+ /**
115
+ * How often a folder name means, or null when it means nothing.
116
+ * `every-5-minutes`, `every-3-hours`, `every-2-weeks`, `every-day`, `hourly`…
117
+ */
118
+ function cadenceFromFolder(folder) {
119
+ const name = String(folder).trim().toLowerCase();
120
+ if (Object.prototype.hasOwnProperty.call(NAMED_FOLDERS, name)) return { ...NAMED_FOLDERS[name] };
121
+ const match = /^every-(?:(\d{1,3})-)?(minute|hour|day|week|month)s?$/.exec(name);
122
+ if (!match) return null;
123
+ const every = match[1] === undefined ? 1 : Number(match[1]);
124
+ if (!Number.isInteger(every) || every < 1) return null;
125
+ const unit = match[2];
126
+ if (unit === "minute" && every < MIN_INTERVAL_MINUTES) return null;
127
+ return { unit, every };
128
+ }
129
+
130
+ /**
131
+ * Whether `path` is a routine, and how often it runs.
132
+ *
133
+ * - `{ kind: "routine", cadence, folder, name }` for
134
+ * `tex/routines/<folder>/<name>.md` or `routines/<folder>/<name>.md` whose
135
+ * folder means a schedule.
136
+ * - `{ kind: "unscheduled", reason }` for a note under either root that will
137
+ * never run, with the reason in words a person can act on.
138
+ * - `null` for anything outside both.
139
+ */
140
+ function routineFromPath(path) {
141
+ const root = routineRootOf(path);
142
+ if (root === null) return null;
143
+ if (!/\.md$/i.test(path)) return null;
144
+ const rest = path.slice(root.length).split("/");
145
+ if (rest.length === 1) {
146
+ return {
147
+ kind: "unscheduled",
148
+ reason: `Put it in a folder that says how often, like ${root}daily/.`,
149
+ };
150
+ }
151
+ if (rest.length > 2) {
152
+ return {
153
+ kind: "unscheduled",
154
+ reason: `Only notes directly inside ${root}${rest[0]}/ run.`,
155
+ };
156
+ }
157
+ const cadence = cadenceFromFolder(rest[0]);
158
+ if (!cadence) {
159
+ const tooFast = /^every-(\d+)-minutes?$/i.exec(rest[0]);
160
+ return {
161
+ kind: "unscheduled",
162
+ reason: tooFast
163
+ ? `The fastest a routine can run is every ${MIN_INTERVAL_MINUTES} minutes.`
164
+ : `"${rest[0]}" isn't a schedule. Use hourly, daily, weekly, monthly or a name like every-3-hours.`,
165
+ };
166
+ }
167
+ return { kind: "routine", cadence, folder: rest[0], name: rest[1].replace(/\.md$/i, "") };
168
+ }
169
+
170
+ /** The `key: value` lines of a note's leading front matter, keys lower-cased. */
171
+ function frontMatter(text) {
172
+ const out = {};
173
+ if (typeof text !== "string") return out;
174
+ const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/);
175
+ if (lines[0] === undefined || lines[0].trim() !== "---") return out;
176
+ for (let i = 1; i < lines.length; i++) {
177
+ const line = lines[i];
178
+ if (line.trim() === "---" || line.trim() === "...") return out;
179
+ const match = /^([A-Za-z][\w-]*)\s*:\s*(.*)$/.exec(line);
180
+ if (!match) continue;
181
+ out[match[1].toLowerCase()] = unquote(match[2].trim());
182
+ }
183
+ // No closing line: it was never front matter.
184
+ return {};
185
+ }
186
+
187
+ function unquote(value) {
188
+ const m = /^(["'])(.*)\1$/.exec(value);
189
+ return m ? m[2] : value;
190
+ }
191
+
192
+ /** `7:30 am`, `7am`, `19:00`, `noon`, `midnight` → `{ hour, minute }`, or null. */
193
+ function parseTime(value) {
194
+ const text = String(value).trim().toLowerCase().replace(/\./g, "");
195
+ if (text === "noon") return { hour: 12, minute: 0 };
196
+ if (text === "midnight") return { hour: 0, minute: 0 };
197
+ const match = /^(\d{1,2})(?::(\d{2}))?\s*(am|pm)?$/.exec(text);
198
+ if (!match) return null;
199
+ let hour = Number(match[1]);
200
+ const minute = match[2] === undefined ? 0 : Number(match[2]);
201
+ const half = match[3];
202
+ if (minute > 59) return null;
203
+ if (half) {
204
+ if (hour < 1 || hour > 12) return null;
205
+ if (half === "am") hour = hour === 12 ? 0 : hour;
206
+ else hour = hour === 12 ? 12 : hour + 12;
207
+ } else if (match[2] === undefined) {
208
+ // A bare "7" is ambiguous between a time and a minute; ask for words.
209
+ return null;
210
+ }
211
+ if (hour > 23) return null;
212
+ return { hour, minute };
213
+ }
214
+
215
+ /** `weekdays`, `weekends`, `friday`, `mon, wed`, `every day` → sorted day numbers (0 = Sunday). */
216
+ function parseWeekdays(value) {
217
+ const text = String(value).trim().toLowerCase();
218
+ if (text === "weekdays" || text === "weekday") return [1, 2, 3, 4, 5];
219
+ if (text === "weekends" || text === "weekend") return [0, 6];
220
+ if (text === "every day" || text === "everyday" || text === "daily") return [0, 1, 2, 3, 4, 5, 6];
221
+ const days = new Set();
222
+ for (const raw of text.split(/\s*(?:,|\band\b|&)\s*/)) {
223
+ const word = raw.trim().replace(/s$/, "");
224
+ if (word === "") continue;
225
+ const index = WEEKDAYS.findIndex((day) => day === word || (word.length >= 3 && day.startsWith(word)));
226
+ if (index === -1) return null;
227
+ days.add(index);
228
+ }
229
+ return days.size === 0 ? null : [...days].sort((a, b) => a - b);
230
+ }
231
+
232
+ /** `2026-10-15` → `{ year, month, day }`, or null for anything else or a date that does not exist. */
233
+ function parseDate(value) {
234
+ const match = /^(\d{4})-(\d{1,2})-(\d{1,2})$/.exec(String(value).trim());
235
+ if (!match) return null;
236
+ const year = Number(match[1]);
237
+ const month = Number(match[2]);
238
+ const day = Number(match[3]);
239
+ if (month < 1 || month > 12 || day < 1 || day > daysInMonth(year, month)) return null;
240
+ return { year, month, day };
241
+ }
242
+
243
+ /**
244
+ * A one-off's `at:`: a date with an optional time, `2026-10-15 9:00 am` or
245
+ * `2026-10-15`. `{ date, time }`, with `time` null when none was written, or
246
+ * null when it isn't a date.
247
+ */
248
+ function parseDateTime(value) {
249
+ const match = /^(\S+)(?:\s+(.+))?$/.exec(String(value).trim());
250
+ if (!match) return null;
251
+ const date = parseDate(match[1]);
252
+ if (!date) return null;
253
+ if (match[2] === undefined) return { date, time: null };
254
+ const time = parseTime(match[2]);
255
+ return time ? { date, time } : null;
256
+ }
257
+
258
+ /** `1`, `1st`, `15th`, `last` → a day of the month (`-1` for the last), or null. */
259
+ function parseMonthDay(value) {
260
+ const text = String(value).trim().toLowerCase().replace(/^the\s+/, "");
261
+ if (text === "last" || text === "last day") return -1;
262
+ const match = /^(\d{1,2})(?:st|nd|rd|th)?$/.exec(text);
263
+ if (!match) return null;
264
+ const day = Number(match[1]);
265
+ return day >= 1 && day <= 31 ? day : null;
266
+ }
267
+
268
+ function isTimeZone(value) {
269
+ try {
270
+ new Intl.DateTimeFormat("en-US", { timeZone: value });
271
+ return true;
272
+ } catch {
273
+ return false;
274
+ }
275
+ }
276
+
277
+ /** A chat routine's `chat:` id: the first 16 hex of the chat's key (`chatRoutineId`). */
278
+ const CHAT_ID = /^[0-9a-f]{16}$/;
279
+
280
+ /** The `chat:` id of a group chat, from its 64-hex key. */
281
+ function chatRoutineId(groupKey) {
282
+ return typeof groupKey === "string" && /^[0-9a-f]{64}$/.test(groupKey) ? groupKey.slice(0, 16) : null;
283
+ }
284
+
285
+ const YES = new Set(["yes", "true", "on", "y"]);
286
+ const NO = new Set(["no", "false", "off", "n", ""]);
287
+
288
+ /**
289
+ * The optional lines of a routine note, read against its cadence.
290
+ *
291
+ * Returns `{ settings, problems }`. A line that is not understood is a problem
292
+ * with a sentence saying how to fix it; it never silently becomes a default,
293
+ * because a routine that quietly runs at the wrong time is worse than one that
294
+ * says it can't read its own time.
295
+ */
296
+ function routineSettings(text, cadence) {
297
+ const fields = frontMatter(text);
298
+ const problems = [];
299
+ const settings = {
300
+ at: null,
301
+ days: null,
302
+ monthDay: null,
303
+ send: "text",
304
+ to: [],
305
+ chat: null,
306
+ wake: null,
307
+ until: null,
308
+ paused: false,
309
+ timeZone: null,
310
+ date: null,
311
+ done: null,
312
+ };
313
+ const once = cadence && cadence.unit === "once";
314
+
315
+ if (once) {
316
+ // A one-off says when in one line, `at: 2026-10-15 9:00 am`, or as a
317
+ // day and a time, `on: 2026-10-15` with `at: 9:00 am`.
318
+ const atDate = fields.at === undefined ? null : parseDateTime(fields.at);
319
+ if (atDate) {
320
+ settings.date = atDate.date;
321
+ settings.at = atDate.time;
322
+ } else if (fields.at !== undefined && fields.at !== "") {
323
+ const at = parseTime(fields.at);
324
+ if (at) settings.at = at;
325
+ else problems.push(`"at: ${fields.at}" isn't a date and time. Write it like 2026-10-15 9:00 am.`);
326
+ }
327
+ if (fields.on !== undefined && fields.on !== "") {
328
+ const date = parseDate(fields.on);
329
+ if (date && settings.date === null) settings.date = date;
330
+ else if (!date) problems.push(`"on: ${fields.on}" isn't a date. Write it like 2026-10-15.`);
331
+ }
332
+ if (settings.date === null && !problems.length) {
333
+ problems.push("A one-off needs a date. Write it like at: 2026-10-15 9:00 am.");
334
+ }
335
+ } else if (fields.at !== undefined && fields.at !== "") {
336
+ const at = parseTime(fields.at);
337
+ if (at) settings.at = at;
338
+ else problems.push(`"at: ${fields.at}" isn't a time. Write it like 7:30 am or 19:00.`);
339
+ }
340
+ if (!once && fields.on !== undefined && fields.on !== "") {
341
+ if (cadence && cadence.unit === "month") {
342
+ const day = parseMonthDay(fields.on);
343
+ if (day !== null) settings.monthDay = day;
344
+ else problems.push(`"on: ${fields.on}" isn't a day of the month. Write it like 1st, 15 or last.`);
345
+ } else if (cadence && cadence.unit === "minute") {
346
+ problems.push(`"on:" doesn't apply to a routine that runs every few minutes.`);
347
+ } else {
348
+ const days = parseWeekdays(fields.on);
349
+ if (days) settings.days = days;
350
+ else problems.push(`"on: ${fields.on}" isn't a day. Write it like friday, weekdays or mon, wed.`);
351
+ }
352
+ }
353
+ if (fields.send !== undefined && fields.send !== "") {
354
+ const send = fields.send.toLowerCase();
355
+ if (send === "text" || send === "note" || send === "both") settings.send = send;
356
+ else problems.push(`"send: ${fields.send}" should be text, note or both.`);
357
+ }
358
+ if (fields.to !== undefined && fields.to !== "") {
359
+ const handles = fields.to
360
+ .replace(/^\[|\]$/g, "")
361
+ .split(/[\s,]+/)
362
+ .filter(Boolean)
363
+ .map((handle) => handle.replace(/^@/, "").toLowerCase());
364
+ if (handles.every((handle) => /^[a-z0-9][a-z0-9_-]{0,38}$/.test(handle))) settings.to = handles;
365
+ else problems.push(`"to: ${fields.to}" should list people as @handles.`);
366
+ }
367
+ // `chat:` names the group chat a shared workspace's routine answers into
368
+ // (`docs/decisions/texting-assistant/chat-routines.md`): the id Tex writes there.
369
+ if (fields.chat !== undefined && fields.chat !== "") {
370
+ const chat = fields.chat.trim().toLowerCase();
371
+ if (CHAT_ID.test(chat)) settings.chat = chat;
372
+ else problems.push(`"chat: ${fields.chat}" isn't a chat. Ask Tex in the chat to set the routine up.`);
373
+ }
374
+ // `wake: new mail` also runs a chat routine soon after new mail reaches a
375
+ // mailbox shared with its chat (`docs/decisions/texting-assistant/chat-mail.md`).
376
+ if (fields.wake !== undefined && fields.wake !== "") {
377
+ if (/^new (?:mail|email)$/i.test(fields.wake.trim())) settings.wake = "mail";
378
+ else problems.push(`"wake: ${fields.wake}" isn't something a routine can wake on. Use "wake: new mail".`);
379
+ }
380
+ if (fields.until !== undefined && fields.until !== "") settings.until = fields.until;
381
+ if (fields.paused !== undefined) {
382
+ const paused = fields.paused.toLowerCase();
383
+ if (YES.has(paused)) settings.paused = true;
384
+ else if (!NO.has(paused)) problems.push(`"paused: ${fields.paused}" should be yes or no.`);
385
+ }
386
+ // `done:` is the time a one-off ran, written by the gateway: it never runs again.
387
+ if (fields.done !== undefined && fields.done !== "") {
388
+ settings.done = fields.done;
389
+ settings.paused = true;
390
+ }
391
+ const zone = fields.timezone ?? fields["time-zone"] ?? fields.tz;
392
+ if (zone !== undefined && zone !== "") {
393
+ if (isTimeZone(zone)) settings.timeZone = zone;
394
+ else problems.push(`"timezone: ${zone}" isn't a time zone. Write it like America/New_York.`);
395
+ }
396
+ if (cadence && cadence.unit === "minute" && settings.at) {
397
+ problems.push(`"at:" doesn't apply to a routine that runs every few minutes.`);
398
+ settings.at = null;
399
+ }
400
+ return { settings, problems };
401
+ }
402
+
403
+ // ── Time ────────────────────────────────────────────────────────────────────
404
+
405
+ const partsFormatters = new Map();
406
+
407
+ function formatterFor(timeZone) {
408
+ let formatter = partsFormatters.get(timeZone);
409
+ if (!formatter) {
410
+ formatter = new Intl.DateTimeFormat("en-US", {
411
+ timeZone,
412
+ hourCycle: "h23",
413
+ year: "numeric",
414
+ month: "numeric",
415
+ day: "numeric",
416
+ hour: "numeric",
417
+ minute: "numeric",
418
+ second: "numeric",
419
+ });
420
+ partsFormatters.set(timeZone, formatter);
421
+ }
422
+ return formatter;
423
+ }
424
+
425
+ /** The wall clock in `timeZone` at instant `ms`. */
426
+ function wallClock(ms, timeZone) {
427
+ const parts = {};
428
+ for (const part of formatterFor(timeZone).formatToParts(new Date(ms))) parts[part.type] = part.value;
429
+ const year = Number(parts.year);
430
+ const month = Number(parts.month);
431
+ const day = Number(parts.day);
432
+ return {
433
+ year,
434
+ month,
435
+ day,
436
+ hour: Number(parts.hour) % 24,
437
+ minute: Number(parts.minute),
438
+ weekday: new Date(Date.UTC(year, month - 1, day)).getUTCDay(),
439
+ };
440
+ }
441
+
442
+ function offsetAt(ms, timeZone) {
443
+ const w = wallClock(ms, timeZone);
444
+ const asUtc = Date.UTC(w.year, w.month - 1, w.day, w.hour, w.minute);
445
+ return asUtc - Math.floor(ms / 60000) * 60000;
446
+ }
447
+
448
+ /**
449
+ * The instant a wall-clock time happens in `timeZone`. A time skipped by a
450
+ * daylight-saving jump lands just after the jump.
451
+ */
452
+ function instantOf(year, month, day, hour, minute, timeZone) {
453
+ const guess = Date.UTC(year, month - 1, day, hour, minute);
454
+ let instant = guess - offsetAt(guess, timeZone);
455
+ const second = guess - offsetAt(instant, timeZone);
456
+ if (second !== instant) instant = Math.max(instant, second);
457
+ return instant;
458
+ }
459
+
460
+ const DAY_MS = 86400000;
461
+
462
+ /** Whole days from 1970-01-01 to a civil date. */
463
+ function dayNumber(year, month, day) {
464
+ return Math.floor(Date.UTC(year, month - 1, day) / DAY_MS);
465
+ }
466
+
467
+ function daysInMonth(year, month) {
468
+ return new Date(Date.UTC(year, month, 0)).getUTCDate();
469
+ }
470
+
471
+ /**
472
+ * When a routine next runs, strictly after `afterMs`, or null if never.
473
+ *
474
+ * Intervals of more than one unit count from a fixed epoch, never from when
475
+ * the file was written, so the answer does not change when a file is re-saved:
476
+ * - every N minutes: minute marks divisible by N since 1970 (UTC);
477
+ * - every N hours: local hours divisible by N, at the `at` minute (default :00);
478
+ * - every N days: local days since 1970 divisible by N;
479
+ * - every N weeks: weeks since Monday 1970-01-05 divisible by N;
480
+ * - every N months: months since January 1970 divisible by N.
481
+ */
482
+ function nextRunAt(cadence, settings, timeZone, afterMs) {
483
+ if (!cadence || !UNITS.includes(cadence.unit)) return null;
484
+ const every = cadence.every || 1;
485
+ const zone = (settings && settings.timeZone) || timeZone || "UTC";
486
+ const at = (settings && settings.at) || DEFAULT_AT;
487
+ const days = settings && settings.days;
488
+
489
+ if (cadence.unit === "once") {
490
+ const date = settings && settings.date;
491
+ if (!date) return null;
492
+ const instant = instantOf(date.year, date.month, date.day, at.hour, at.minute, zone);
493
+ return instant > afterMs ? instant : null;
494
+ }
495
+
496
+ if (cadence.unit === "minute") {
497
+ const step = every * 60000;
498
+ return Math.floor(afterMs / step) * step + step;
499
+ }
500
+
501
+ if (cadence.unit === "hour") {
502
+ const minute = settings && settings.at ? settings.at.minute : 0;
503
+ const start = Math.floor(afterMs / 3600000) * 3600000 - 3600000;
504
+ for (let i = 0; i < 24 * 8 * every + 48; i++) {
505
+ const w = wallClock(start + i * 3600000, zone);
506
+ if (w.hour % every !== 0) continue;
507
+ if (days && !days.includes(w.weekday)) continue;
508
+ const candidate = instantOf(w.year, w.month, w.day, w.hour, minute, zone);
509
+ if (candidate > afterMs) return candidate;
510
+ }
511
+ return null;
512
+ }
513
+
514
+ const today = wallClock(afterMs, zone);
515
+ const first = dayNumber(today.year, today.month, today.day) - 1;
516
+ const horizon = cadence.unit === "month" ? 31 * 13 * every : 8 * 7 * every + 8;
517
+ for (let i = 0; i < horizon; i++) {
518
+ const date = new Date((first + i) * DAY_MS);
519
+ const year = date.getUTCFullYear();
520
+ const month = date.getUTCMonth() + 1;
521
+ const day = date.getUTCDate();
522
+ const weekday = date.getUTCDay();
523
+ const n = first + i;
524
+
525
+ if (cadence.unit === "day") {
526
+ if (n % every !== 0) continue;
527
+ if (days && !days.includes(weekday)) continue;
528
+ } else if (cadence.unit === "week") {
529
+ const wanted = days || [1];
530
+ if (!wanted.includes(weekday)) continue;
531
+ // 1970-01-05 was a Monday: day number 4.
532
+ const week = Math.floor((n - 4) / 7);
533
+ if (((week % every) + every) % every !== 0) continue;
534
+ } else if (cadence.unit === "month") {
535
+ const monthIndex = (year - 1970) * 12 + (month - 1);
536
+ if (monthIndex % every !== 0) continue;
537
+ const wantedDay = settings && settings.monthDay !== null && settings.monthDay !== undefined ? settings.monthDay : 1;
538
+ const last = daysInMonth(year, month);
539
+ const target = wantedDay === -1 ? last : Math.min(wantedDay, last);
540
+ if (day !== target) continue;
541
+ }
542
+ const candidate = instantOf(year, month, day, at.hour, at.minute, zone);
543
+ if (candidate > afterMs) return candidate;
544
+ }
545
+ return null;
546
+ }
547
+
548
+ // ── Words ───────────────────────────────────────────────────────────────────
549
+
550
+ function clock(at) {
551
+ const hour = at.hour % 12 === 0 ? 12 : at.hour % 12;
552
+ const minute = at.minute === 0 ? "" : `:${String(at.minute).padStart(2, "0")}`;
553
+ return `${hour}${minute} ${at.hour < 12 ? "am" : "pm"}`;
554
+ }
555
+
556
+ function dayList(days) {
557
+ const key = days.join(",");
558
+ if (key === "1,2,3,4,5") return "weekdays";
559
+ if (key === "0,6") return "weekends";
560
+ if (key === "0,1,2,3,4,5,6") return "every day";
561
+ const names = days.map((d) => WEEKDAYS[d][0].toUpperCase() + WEEKDAYS[d].slice(1, 3));
562
+ return names.length === 1 ? `${WEEKDAYS[days[0]][0].toUpperCase()}${WEEKDAYS[days[0]].slice(1)}s` : names.join(", ");
563
+ }
564
+
565
+ function ordinal(n) {
566
+ if (n === -1) return "last day";
567
+ const rem = n % 100;
568
+ if (rem >= 11 && rem <= 13) return `${n}th`;
569
+ return `${n}${["th", "st", "nd", "rd"][n % 10] || "th"}`;
570
+ }
571
+
572
+ /** "Every day at 7:30 am", "Weekdays at 9 am", "Every 5 minutes", "Fridays at 4 pm". */
573
+ function describeSchedule(cadence, settings) {
574
+ const at = (settings && settings.at) || DEFAULT_AT;
575
+ const days = settings && settings.days;
576
+ const every = cadence.every || 1;
577
+ switch (cadence.unit) {
578
+ case "once": {
579
+ const date = settings && settings.date;
580
+ if (!date) return "Once, when it has a date";
581
+ const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
582
+ const day = `${months[date.month - 1]} ${date.day}, ${date.year}`;
583
+ return `${settings.done ? "Ran once" : "Once"} on ${day} at ${clock(at)}`;
584
+ }
585
+ case "minute":
586
+ return `Every ${every} minutes`;
587
+ case "hour": {
588
+ const base = every === 1 ? "Every hour" : `Every ${every} hours`;
589
+ const minute = settings && settings.at ? settings.at.minute : 0;
590
+ const tail = minute === 0 ? "" : ` at :${String(minute).padStart(2, "0")}`;
591
+ return `${base}${tail}${days ? `, ${dayList(days)}` : ""}`;
592
+ }
593
+ case "day":
594
+ if (every === 1) {
595
+ if (days && days.length < 7) {
596
+ const words = dayList(days);
597
+ return `${words[0].toUpperCase()}${words.slice(1)} at ${clock(at)}`;
598
+ }
599
+ return `Every day at ${clock(at)}`;
600
+ }
601
+ return `Every ${every} days at ${clock(at)}`;
602
+ case "week": {
603
+ const words = dayList(days || [1]);
604
+ const lead = every === 1 ? `${words[0].toUpperCase()}${words.slice(1)}` : `Every ${every} weeks on ${words}`;
605
+ return `${lead} at ${clock(at)}`;
606
+ }
607
+ case "month": {
608
+ const day = settings && settings.monthDay !== null && settings.monthDay !== undefined ? settings.monthDay : 1;
609
+ const lead = every === 1 ? "Monthly" : every === 12 ? "Yearly" : `Every ${every} months`;
610
+ return `${lead} on the ${ordinal(day)} at ${clock(at)}`;
611
+ }
612
+ default:
613
+ return "";
614
+ }
615
+ }
616
+
617
+ /**
618
+ * The run history file for a routine at `path`, under its own root's prefix so
619
+ * the two roots never share one.
620
+ */
621
+ function routineRunsKey(path) {
622
+ const root = routineRootOf(path) || ROUTINES_FOLDER;
623
+ return `${ROUTINE_RUNS_PREFIXES[root]}${path.slice(root.length).replace(/\.md$/i, "")}.json`;
624
+ }
625
+
626
+ /** The routines' default zone when an account has none (Convex `DEFAULT_ROUTINE_TIME_ZONE`). */
627
+ const DEFAULT_ROUTINE_TIME_ZONE = "America/New_York";
628
+
629
+ module.exports = {
630
+ DEFAULT_ROUTINE_TIME_ZONE,
631
+ ROUTINES_FOLDER,
632
+ TEX_ROUTINES_FOLDER,
633
+ ROUTINE_ROOTS,
634
+ ROUTINE_RUNS_PREFIX,
635
+ ROUTINE_RUNS_PREFIXES,
636
+ MIN_INTERVAL_MINUTES,
637
+ DEFAULT_AT,
638
+ cadenceFromFolder,
639
+ routineFromPath,
640
+ routineRootOf,
641
+ isRoutinePath,
642
+ homeRoutineOf,
643
+ isHomeRoutinePath,
644
+ frontMatter,
645
+ parseTime,
646
+ parseWeekdays,
647
+ parseMonthDay,
648
+ parseDate,
649
+ parseDateTime,
650
+ routineSettings,
651
+ chatRoutineId,
652
+ nextRunAt,
653
+ describeSchedule,
654
+ routineRunsKey,
655
+ wallClock,
656
+ };