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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +33 -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/capabilities.cjs +47 -0
  23. package/texContract/capabilities.d.cts +27 -0
  24. package/texContract/capabilities.generated.json +77 -0
  25. package/texContract/chatHistoryPath.cjs +38 -0
  26. package/texContract/chatHistoryPath.d.cts +5 -0
  27. package/texContract/chatLedger.cjs +91 -0
  28. package/texContract/chatLedger.d.cts +21 -0
  29. package/texContract/computerTool.cjs +102 -0
  30. package/texContract/computerTool.d.cts +16 -0
  31. package/texContract/consentYes.cjs +22 -0
  32. package/texContract/consentYes.d.cts +5 -0
  33. package/texContract/contextGateway.cjs +52 -0
  34. package/texContract/contextGateway.d.cts +19 -0
  35. package/texContract/deskEligible.cjs +20 -0
  36. package/texContract/deskEligible.d.cts +3 -0
  37. package/texContract/downloads.cjs +129 -0
  38. package/texContract/downloads.d.cts +15 -0
  39. package/texContract/egressLedger.cjs +114 -0
  40. package/texContract/egressLedger.d.cts +14 -0
  41. package/texContract/emailRead.cjs +38 -0
  42. package/texContract/emailRead.d.cts +5 -0
  43. package/texContract/eventWords.cjs +35 -0
  44. package/texContract/eventWords.d.cts +4 -0
  45. package/texContract/fileParts.cjs +43 -0
  46. package/texContract/fileParts.d.cts +6 -0
  47. package/texContract/fileTables.cjs +243 -0
  48. package/texContract/fileWords.cjs +169 -0
  49. package/texContract/folded.cjs +16 -0
  50. package/texContract/folded.d.cts +3 -0
  51. package/texContract/googleAiAccess.cjs +12 -0
  52. package/texContract/googleAiAccess.d.cts +2 -0
  53. package/texContract/graphWires.cjs +18 -0
  54. package/texContract/graphWires.d.cts +5 -0
  55. package/texContract/groupSession.cjs +28 -0
  56. package/texContract/groupSession.d.cts +7 -0
  57. package/texContract/guestNames.cjs +136 -0
  58. package/texContract/guestNames.d.cts +35 -0
  59. package/texContract/heard.cjs +19 -0
  60. package/texContract/heard.d.cts +4 -0
  61. package/texContract/heldOffer.cjs +57 -0
  62. package/texContract/heldOffer.d.cts +8 -0
  63. package/texContract/helperCallers.cjs +29 -0
  64. package/texContract/helperCallers.d.cts +4 -0
  65. package/texContract/identity.cjs +179 -0
  66. package/texContract/identity.d.cts +8 -0
  67. package/texContract/jobLogEntries.cjs +93 -0
  68. package/texContract/jobLogEntries.d.cts +12 -0
  69. package/texContract/judgedActions.cjs +20 -0
  70. package/texContract/judgedActions.d.cts +4 -0
  71. package/texContract/labSandboxGate.cjs +63 -0
  72. package/texContract/labSandboxGate.d.cts +9 -0
  73. package/texContract/ledgerReadChars.cjs +4 -0
  74. package/texContract/ledgerReadChars.d.cts +3 -0
  75. package/texContract/mailCheck.cjs +90 -0
  76. package/texContract/mailCheck.d.cts +12 -0
  77. package/texContract/mailEntries.cjs +64 -0
  78. package/texContract/mailEntries.d.cts +13 -0
  79. package/texContract/mailHealth.cjs +60 -0
  80. package/texContract/mailHealth.d.cts +10 -0
  81. package/texContract/notePath.cjs +99 -0
  82. package/texContract/notePath.d.cts +4 -0
  83. package/texContract/noteRunFacts.cjs +136 -0
  84. package/texContract/noteRunFacts.d.cts +32 -0
  85. package/texContract/objectEtag.cjs +84 -0
  86. package/texContract/objectEtag.d.cts +4 -0
  87. package/texContract/objectPlace.cjs +32 -0
  88. package/texContract/objectPlace.d.cts +5 -0
  89. package/texContract/pageJobs.cjs +226 -0
  90. package/texContract/pageJobs.d.cts +13 -0
  91. package/texContract/pdfLinks.cjs +135 -0
  92. package/texContract/pdfLinks.d.cts +4 -0
  93. package/texContract/personHub.cjs +38 -0
  94. package/texContract/personHub.d.cts +5 -0
  95. package/texContract/personNameText.cjs +18 -0
  96. package/texContract/personNameText.d.cts +3 -0
  97. package/texContract/pinnedContext.cjs +12 -0
  98. package/texContract/pinnedContext.d.cts +3 -0
  99. package/texContract/quietHoursWindow.cjs +36 -0
  100. package/texContract/quietHoursWindow.d.cts +3 -0
  101. package/texContract/reactEmoji.cjs +79 -0
  102. package/texContract/reactEmoji.d.cts +2 -0
  103. package/texContract/scopeClamp.cjs +117 -0
  104. package/texContract/scopeClamp.d.cts +5 -0
  105. package/texContract/scopes.cjs +29 -0
  106. package/texContract/scopes.d.cts +7 -0
  107. package/texContract/searchSettings.cjs +54 -0
  108. package/texContract/searchSettings.d.cts +6 -0
  109. package/texContract/settingHabits.cjs +87 -0
  110. package/texContract/settingHabits.d.cts +20 -0
  111. package/texContract/settingsNotes.cjs +217 -0
  112. package/texContract/settingsNotes.d.cts +26 -0
  113. package/texContract/shownEmail.cjs +181 -0
  114. package/texContract/texClients.cjs +53 -0
  115. package/texContract/texClients.d.cts +12 -0
  116. package/texContract/texGraph.cjs +593 -0
  117. package/texContract/texGraph.d.cts +55 -0
  118. package/texContract/texKeys.cjs +100 -0
  119. package/texContract/texKeys.d.cts +13 -0
  120. package/texContract/texNumber.cjs +20 -0
  121. package/texContract/texNumber.d.cts +3 -0
  122. package/texContract/texOwnSources.cjs +9 -0
  123. package/texContract/texOwnSources.d.cts +3 -0
  124. package/texContract/texSettings.cjs +22 -0
  125. package/texContract/texSettings.d.cts +20 -0
  126. package/texContract/texSettings.generated.json +25 -0
  127. package/texContract/texStateFiles.cjs +22 -0
  128. package/texContract/texStateFiles.d.cts +9 -0
  129. package/texContract/texSteps.cjs +27 -0
  130. package/texContract/texSteps.d.cts +14 -0
  131. package/texContract/texSteps.generated.json +41 -0
  132. package/texContract/texStoreNames.cjs +26 -0
  133. package/texContract/texStoreNames.d.cts +12 -0
  134. package/texContract/texStoreWire.cjs +306 -0
  135. package/texContract/texStoreWire.d.cts +32 -0
  136. package/texContract/threadsFold.cjs +75 -0
  137. package/texContract/threadsFold.d.cts +22 -0
  138. package/texContract/toolActions.cjs +253 -0
  139. package/texContract/toolCatalog.cjs +49 -0
  140. package/texContract/toolCatalog.generated.json +90 -0
  141. package/texContract/toolContract.cjs +52 -0
  142. package/texContract/toolContract.d.cts +12 -0
  143. package/texContract/toolShapes.cjs +14 -0
  144. package/texContract/transcription.cjs +101 -0
  145. package/texContract/transcription.d.cts +3 -0
  146. package/texContract/treeJobs.cjs +31 -0
  147. package/texContract/treeJobs.d.cts +3 -0
  148. package/texContract/turnSession.cjs +90 -0
  149. package/texContract/turnSession.d.cts +19 -0
  150. package/texContract/turnWords.cjs +90 -0
  151. package/texContract/turnWords.d.cts +9 -0
  152. package/texContract/uploadImages.cjs +131 -0
  153. package/texContract/uploadImages.d.cts +13 -0
  154. package/texContract/v2Names.cjs +41 -0
  155. package/texContract/v2SearchFetch.cjs +316 -0
  156. package/texContract/v2Translate.cjs +123 -0
  157. package/texContract/vaultTools.cjs +112 -0
  158. package/texContract/vaultTools.d.cts +15 -0
  159. package/texContract/yesWords.cjs +91 -0
  160. package/texShared/argumentCoercion.cjs +93 -0
  161. package/texShared/cellComments.cjs +122 -0
  162. package/texShared/cellComments.d.cts +21 -0
  163. package/texShared/comments.cjs +586 -0
  164. package/texShared/comments.d.cts +115 -0
  165. package/texShared/contentTypes.cjs +85 -0
  166. package/texShared/fileKinds.cjs +123 -0
  167. package/texShared/flags.cjs +159 -0
  168. package/texShared/flags.d.cts +23 -0
  169. package/texShared/folderJobInfo.cjs +301 -0
  170. package/texShared/folderJobInfo.d.cts +40 -0
  171. package/texShared/folderRoles.cjs +512 -0
  172. package/texShared/folderRoles.d.cts +73 -0
  173. package/texShared/githubOidc.ts +98 -0
  174. package/texShared/groupRunQuestions.cjs +98 -0
  175. package/texShared/groupRunQuestions.d.cts +4 -0
  176. package/texShared/inboxFolders.cjs +49 -0
  177. package/texShared/inboxFolders.d.cts +5 -0
  178. package/texShared/ink/drawing.cjs +474 -0
  179. package/texShared/ink/texFigure.cjs +252 -0
  180. package/texShared/ink/texFigure.d.cts +36 -0
  181. package/texShared/ink/texPoses.cjs +180 -0
  182. package/texShared/ink/texPoses.d.cts +20 -0
  183. package/texShared/jobPartEnd.cjs +133 -0
  184. package/texShared/jobPartEnd.d.cts +13 -0
  185. package/texShared/jobResume.cjs +31 -0
  186. package/texShared/jobResume.d.cts +5 -0
  187. package/texShared/jobSplit.cjs +90 -0
  188. package/texShared/jobSplit.d.cts +6 -0
  189. package/texShared/jobStart.cjs +56 -0
  190. package/texShared/jobStart.d.cts +9 -0
  191. package/texShared/mail.cjs +400 -0
  192. package/texShared/mail.d.cts +56 -0
  193. package/texShared/messageAnchors.cjs +38 -0
  194. package/texShared/models/aiKeys.cjs +137 -0
  195. package/texShared/models/aiKeys.d.cts +42 -0
  196. package/texShared/models/aiKeys.json +56 -0
  197. package/texShared/models/creditRest.cjs +269 -0
  198. package/texShared/models/promptBudget.cjs +295 -0
  199. package/texShared/models/promptSections.cjs +29 -0
  200. package/texShared/noteAppLink.cjs +23 -0
  201. package/texShared/notePreview.cjs +219 -0
  202. package/texShared/notePreview.d.cts +21 -0
  203. package/texShared/pages/blocks.cjs +215 -0
  204. package/texShared/pages/cover.cjs +164 -0
  205. package/texShared/pages/css.cjs +181 -0
  206. package/texShared/pages/cssBlocks.cjs +264 -0
  207. package/texShared/pages/draw.cjs +212 -0
  208. package/texShared/pages/drawRich.cjs +232 -0
  209. package/texShared/pages/html.cjs +168 -0
  210. package/texShared/pages/inline.cjs +251 -0
  211. package/texShared/pages/layout.cjs +76 -0
  212. package/texShared/pages/parse.cjs +418 -0
  213. package/texShared/pages/render.cjs +200 -0
  214. package/texShared/pages/skill.cjs +147 -0
  215. package/texShared/pages/skill.d.cts +5 -0
  216. package/texShared/pages/templates.cjs +336 -0
  217. package/texShared/r2Store.cjs +163 -0
  218. package/texShared/remoteImage.cjs +177 -0
  219. package/texShared/routines.cjs +656 -0
  220. package/texShared/routines.d.cts +86 -0
  221. package/texShared/servedListing.cjs +250 -0
  222. package/texShared/servedListing.d.cts +17 -0
  223. package/texShared/sheetCsv.cjs +566 -0
  224. package/texShared/sheetCsv.d.cts +91 -0
  225. package/texShared/storageLayout.cjs +88 -0
  226. package/texShared/storeKeys.cjs +144 -0
  227. package/texShared/toolArguments.cjs +323 -0
@@ -0,0 +1,586 @@
1
+ /**
2
+ * Comments on a note, kept in the note's own file.
3
+ *
4
+ * ## The format
5
+ *
6
+ * A comment is about a stretch of text, so it has two halves, and both are
7
+ * plain Markdown that any editor keeps:
8
+ *
9
+ * - **An anchor**: a pair of HTML comments around the words, as in
10
+ * `<!--c:k7f2-->free, you cheapo<!--/c:k7f2-->`. HTML comments render as
11
+ * nothing in Obsidian, on GitHub and in our own reader, so the note still
12
+ * reads as the note. Pairs are matched by id, never by nesting, so two
13
+ * anchors may overlap.
14
+ * - **The threads**: one fenced block with the info string `comments`, at the
15
+ * end of the note. Each thread is a header line (its id and the quoted words
16
+ * as a JSON string) and then one line per thing that happened:
17
+ *
18
+ * ```comments
19
+ * k7f2 "free, you cheapo"
20
+ * - 2026-09-27T07:30:12Z Codex: This seems a little unprofessional.
21
+ * - 2026-09-27T07:31:40Z Dev2: eh, I don't really care
22
+ * - 2026-09-27T07:31:45Z Dev2 resolved
23
+ * ```
24
+ *
25
+ * A comment's later lines are indented four spaces, which is deeper than a
26
+ * closing fence may be indented, so no comment can end the block early.
27
+ *
28
+ * ## Why an append-only log
29
+ *
30
+ * Resolving never removes anything: it adds a `resolved` line, and reopening
31
+ * adds a `reopened` one. A thread's status is whichever of those came last.
32
+ * That keeps the whole history in the file (Dev2 asked for Google Docs'
33
+ * "see resolved comments"), and it makes every change but a delete an
34
+ * insertion (`deleteComment` says why that one removes). Two people
35
+ * replying at once are two insertions, which the collaborative editor merges
36
+ * without either reply being lost; a format that rewrote a status field in
37
+ * place would have had them fight over one line.
38
+ *
39
+ * ## Why edits are returned as changes, not as a new file
40
+ *
41
+ * Every operation here returns `{ from, to, insert }` changes against the text
42
+ * it was given, and `applyChanges` turns them into the new text. The gateway
43
+ * applies them to the note it just read; the editor dispatches them as
44
+ * CodeMirror changes so that a comment typed while somebody else is typing in
45
+ * the same note lands as a small insertion rather than as a whole-document
46
+ * replacement. Lines this module does not understand are never rewritten, so a
47
+ * hand edit in Obsidian survives the next comment.
48
+ *
49
+ * Shared by the gateway (`apps/mcp`), the console and the renderers that must
50
+ * never publish comments (share links, websites). One parser, so the three can
51
+ * never disagree about where the block starts.
52
+ */
53
+
54
+ "use strict";
55
+
56
+ const ID = "[a-z0-9]{4,12}";
57
+ const ID_RE = new RegExp(`^${ID}$`);
58
+ const OPEN_RE = new RegExp(`<!--c:(${ID})-->`, "g");
59
+ const CLOSE_RE = new RegExp(`<!--/c:(${ID})-->`, "g");
60
+ const MARKER_RE = new RegExp(`<!--/?c:${ID}-->`, "g");
61
+ const HEADER_RE = new RegExp(`^(${ID})[ \\t]+("(?:[^"\\\\]|\\\\.)*")[ \\t]*$`);
62
+ const COMMENT_RE = /^- (\S+) ([^:\n]+?): ?(.*)$/;
63
+ const STATUS_RE = /^- (\S+) ([^:\n]+?) (resolved|reopened|kept|undid)[ \t]*$/;
64
+ /** Tex's suggested replacement for the anchored words, as one JSON string: `- <at> Tex suggests: "…"`. */
65
+ const SUGGEST_RE = /^- (\S+) ([^:\n]+?) suggests: ("(?:[^"\\]|\\.)*")[ \t]*$/;
66
+ /** The status words: a name ending in one would read back as a status line. */
67
+ const STATUS_WORDS = /\s(resolved|reopened|kept|undid|suggests)$/i;
68
+ const CONTINUATION = " ";
69
+
70
+ /** Longest author name kept; longer ones are cut. */
71
+ const MAX_AUTHOR = 60;
72
+
73
+ function openMarker(id) {
74
+ return `<!--c:${id}-->`;
75
+ }
76
+ function closeMarker(id) {
77
+ return `<!--/c:${id}-->`;
78
+ }
79
+
80
+ /**
81
+ * Lines with their offsets, so a block can be found and edited in place.
82
+ * `end` excludes the newline; `next` is where the following line starts.
83
+ */
84
+ function lines(text) {
85
+ const out = [];
86
+ let start = 0;
87
+ while (start <= text.length) {
88
+ const nl = text.indexOf("\n", start);
89
+ const end = nl === -1 ? text.length : nl;
90
+ const raw = text.slice(start, end);
91
+ out.push({ start, end, next: nl === -1 ? text.length : nl + 1, text: raw.endsWith("\r") ? raw.slice(0, -1) : raw });
92
+ if (nl === -1) break;
93
+ start = nl + 1;
94
+ }
95
+ return out;
96
+ }
97
+
98
+ /** Where frontmatter ends, or 0. A leading `---` line closed by another. */
99
+ function frontmatterEnd(text) {
100
+ if (!/^---\r?\n/.test(text)) return 0;
101
+ const rows = lines(text);
102
+ for (let i = 1; i < rows.length; i += 1) {
103
+ if (/^(---|\.\.\.)\s*$/.test(rows[i].text)) return rows[i].next;
104
+ }
105
+ return 0;
106
+ }
107
+
108
+ /**
109
+ * Every fenced block outside frontmatter, as `{ start, end, info, bodyStart, bodyEnd }`.
110
+ * `start` is the opening fence line, `end` the offset after the closing fence
111
+ * line (or the end of the text when the fence is never closed).
112
+ */
113
+ function fencedBlocks(text) {
114
+ const rows = lines(text);
115
+ const skip = frontmatterEnd(text);
116
+ const blocks = [];
117
+ let open = null;
118
+ for (const row of rows) {
119
+ if (row.start < skip) continue;
120
+ if (!open) {
121
+ const m = /^ {0,3}(`{3,}|~{3,})\s*([^\s`]*)[^`]*$/.exec(row.text);
122
+ if (m) open = { start: row.start, fence: m[1], info: m[2], bodyStart: row.next };
123
+ continue;
124
+ }
125
+ const close = /^ {0,3}(`{3,}|~{3,})\s*$/.exec(row.text);
126
+ if (close && close[1][0] === open.fence[0] && close[1].length >= open.fence.length) {
127
+ blocks.push({ start: open.start, end: row.next, info: open.info, bodyStart: open.bodyStart, bodyEnd: row.start, closed: true });
128
+ open = null;
129
+ }
130
+ }
131
+ if (open) blocks.push({ start: open.start, end: text.length, info: open.info, bodyStart: open.bodyStart, bodyEnd: text.length, closed: false });
132
+ return blocks;
133
+ }
134
+
135
+ /** The note's comments block, the last one if a note somehow has two. */
136
+ function findBlock(text) {
137
+ const blocks = fencedBlocks(text).filter((block) => block.info === "comments" && block.closed);
138
+ return blocks.length ? blocks[blocks.length - 1] : null;
139
+ }
140
+
141
+ /**
142
+ * Every anchor, by id, with the offsets of both markers. Unpaired markers are
143
+ * left out, and so is anything inside a fenced block — the comments block
144
+ * itself, and a code sample that shows the format (like
145
+ * docs/decisions/comments.md) rather than using it.
146
+ */
147
+ function findAnchors(text) {
148
+ const fences = fencedBlocks(text);
149
+ const inBlock = (at) => fences.some((block) => at >= block.start && at < block.end);
150
+ const opens = new Map();
151
+ const anchors = new Map();
152
+ for (const m of text.matchAll(OPEN_RE)) {
153
+ if (!inBlock(m.index) && !opens.has(m[1])) opens.set(m[1], { start: m.index, end: m.index + m[0].length });
154
+ }
155
+ for (const m of text.matchAll(CLOSE_RE)) {
156
+ const open = opens.get(m[1]);
157
+ if (!open || inBlock(m.index) || m.index < open.end || anchors.has(m[1])) continue;
158
+ anchors.set(m[1], {
159
+ id: m[1],
160
+ openStart: open.start,
161
+ from: open.end,
162
+ to: m.index,
163
+ closeEnd: m.index + m[0].length,
164
+ });
165
+ }
166
+ return anchors;
167
+ }
168
+
169
+ /**
170
+ * The note's threads, in the order the block lists them.
171
+ *
172
+ * Each is `{ id, quote, events, status, anchored, headerStart, end }`, where an
173
+ * event is `{ at, author, kind: "comment" | "resolved" | "reopened", text,
174
+ * start, end }` (`[start, end)` covering its lines) and a thread's `end` is the
175
+ * offset just after its last line (where the next event goes). Lines the parser does not recognise are skipped, never fatal:
176
+ * this reads files people edit by hand.
177
+ */
178
+ function parseComments(text) {
179
+ const source = typeof text === "string" ? text : "";
180
+ const block = findBlock(source);
181
+ const anchors = findAnchors(source);
182
+ if (!block) return { block: null, threads: [], anchors };
183
+ const threads = [];
184
+ let thread = null;
185
+ let lastComment = null;
186
+ for (const row of lines(source.slice(block.bodyStart, block.bodyEnd))) {
187
+ const at = block.bodyStart + row.start;
188
+ const next = block.bodyStart + row.next;
189
+ if (block.bodyStart + row.start >= block.bodyEnd) break;
190
+ const header = HEADER_RE.exec(row.text);
191
+ if (header) {
192
+ let quote = "";
193
+ try {
194
+ quote = JSON.parse(header[2]);
195
+ } catch {
196
+ quote = header[2].slice(1, -1);
197
+ }
198
+ thread = { id: header[1], quote, events: [], status: "open", anchored: anchors.has(header[1]), headerStart: at, end: Math.min(next, block.bodyEnd) };
199
+ threads.push(thread);
200
+ lastComment = null;
201
+ continue;
202
+ }
203
+ if (!thread) continue;
204
+ if (row.text.startsWith(CONTINUATION) && lastComment) {
205
+ lastComment.text += `\n${row.text.slice(CONTINUATION.length)}`;
206
+ lastComment.end = Math.min(next, block.bodyEnd);
207
+ thread.end = lastComment.end;
208
+ continue;
209
+ }
210
+ const suggestion = SUGGEST_RE.exec(row.text);
211
+ if (suggestion) {
212
+ lastComment = null;
213
+ let words = "";
214
+ try {
215
+ words = JSON.parse(suggestion[3]);
216
+ } catch {
217
+ words = suggestion[3].slice(1, -1);
218
+ }
219
+ thread.events.push({ at: suggestion[1], author: suggestion[2], kind: "suggestion", text: String(words), start: at, end: Math.min(next, block.bodyEnd) });
220
+ thread.end = Math.min(next, block.bodyEnd);
221
+ continue;
222
+ }
223
+ const comment = COMMENT_RE.exec(row.text);
224
+ const status = comment ? null : STATUS_RE.exec(row.text);
225
+ if (comment) {
226
+ lastComment = { at: comment[1], author: comment[2], kind: "comment", text: comment[3], start: at, end: Math.min(next, block.bodyEnd) };
227
+ thread.events.push(lastComment);
228
+ thread.end = Math.min(next, block.bodyEnd);
229
+ } else if (status) {
230
+ lastComment = null;
231
+ thread.events.push({ at: status[1], author: status[2], kind: status[3], text: "", start: at, end: Math.min(next, block.bodyEnd) });
232
+ if (status[3] === "resolved" || status[3] === "reopened") thread.status = status[3] === "resolved" ? "resolved" : "open";
233
+ thread.end = Math.min(next, block.bodyEnd);
234
+ } else if (row.text.trim() === "") {
235
+ lastComment = null;
236
+ }
237
+ }
238
+ for (const t of threads) t.pending = pendingOf(t);
239
+ return { block, threads, anchors };
240
+ }
241
+
242
+ /**
243
+ * The suggestion still waiting for Keep or Undo: the thread's last
244
+ * `suggests` line with no `kept` or `undid` after it. A newer suggestion
245
+ * replaces an older one, which is how a follow-up revises a pending edit.
246
+ */
247
+ function pendingOf(thread) {
248
+ for (let i = thread.events.length - 1; i >= 0; i -= 1) {
249
+ const event = thread.events[i];
250
+ if (event.kind === "kept" || event.kind === "undid") return null;
251
+ if (event.kind === "suggestion") return { text: event.text, at: event.at, author: event.author, index: i };
252
+ }
253
+ return null;
254
+ }
255
+
256
+ /** A display name made safe for the author slot: one line, no colon, bounded. */
257
+ function sanitizeAuthor(name) {
258
+ const cleaned = String(name ?? "")
259
+ .replace(/[\u0000-\u001f\u007f\u2028\u2029]/g, " ")
260
+ .replace(/:/g, "")
261
+ .replace(/\s+/g, " ")
262
+ .trim()
263
+ .slice(0, MAX_AUTHOR)
264
+ .trim();
265
+ // A name that ends in the status words would read back as a status line.
266
+ if (!cleaned || STATUS_WORDS.test(` ${cleaned}`)) return cleaned ? `${cleaned}.` : "Someone";
267
+ return cleaned;
268
+ }
269
+
270
+ /** A comment body as log lines: the first after the colon, the rest indented. */
271
+ function formatBody(body) {
272
+ const rows = String(body ?? "").replace(/\r\n?/g, "\n").replace(/[\u2028\u2029]/g, "\n").trim().split("\n");
273
+ return rows.map((row, i) => (i === 0 ? row : `${CONTINUATION}${row}`)).join("\n");
274
+ }
275
+
276
+ function eventLine({ at, author, kind, text }) {
277
+ const who = sanitizeAuthor(author);
278
+ if (kind === "resolved" || kind === "reopened" || kind === "kept" || kind === "undid") return `- ${at} ${who} ${kind}`;
279
+ if (kind === "suggestion") return `- ${at} ${who} suggests: ${JSON.stringify(String(text ?? ""))}`;
280
+ return `- ${at} ${who}: ${formatBody(text)}`;
281
+ }
282
+
283
+ function isoNow(at) {
284
+ const date = at instanceof Date ? at : at === undefined ? new Date() : new Date(at);
285
+ return date.toISOString().replace(/\.\d{3}Z$/, "Z");
286
+ }
287
+
288
+ /** A fresh id not already used in this note. `random` is injectable for tests. */
289
+ function newThreadId(text, random = Math.random) {
290
+ const used = new Set([...parseComments(text).threads.map((t) => t.id), ...findAnchors(text).keys()]);
291
+ for (let attempt = 0; attempt < 100; attempt += 1) {
292
+ let id = "";
293
+ for (let i = 0; i < 4 + Math.floor(attempt / 25); i += 1) id += "abcdefghijklmnopqrstuvwxyz0123456789"[Math.floor(random() * 36)];
294
+ if (!used.has(id) && /[a-z]/.test(id[0])) return id;
295
+ }
296
+ throw new Error("could not choose a comment id");
297
+ }
298
+
299
+ /**
300
+ * The note as a reader sees it for matching purposes: markers removed, with a
301
+ * map from each visible offset back to the file.
302
+ */
303
+ function visibleIndex(text) {
304
+ let plain = "";
305
+ const map = [];
306
+ let at = 0;
307
+ for (const m of text.matchAll(MARKER_RE)) {
308
+ for (let i = at; i < m.index; i += 1) {
309
+ map.push(i);
310
+ plain += text[i];
311
+ }
312
+ at = m.index + m[0].length;
313
+ }
314
+ for (let i = at; i < text.length; i += 1) {
315
+ map.push(i);
316
+ plain += text[i];
317
+ }
318
+ map.push(text.length);
319
+ return { plain, map };
320
+ }
321
+
322
+ /** Regions a comment may not be anchored in: frontmatter and every fenced block. */
323
+ function forbiddenRegions(text) {
324
+ const regions = [];
325
+ const fm = frontmatterEnd(text);
326
+ if (fm) regions.push([0, fm]);
327
+ for (const block of fencedBlocks(text)) regions.push([block.start, block.end]);
328
+ return regions;
329
+ }
330
+
331
+ /** Inside an inline code span on its line: an odd number of backticks before it. */
332
+ function insideInlineCode(text, at) {
333
+ const lineStart = text.lastIndexOf("\n", at - 1) + 1;
334
+ return ((text.slice(lineStart, at).match(/`/g) || []).length % 2) === 1;
335
+ }
336
+
337
+ /**
338
+ * Where `quote` sits, as file offsets `[from, to)`, or an error a caller can
339
+ * show. `occurrence` is 1-based and defaults to 1; a quote that appears more
340
+ * than once without one is refused, so an agent never anchors the wrong copy.
341
+ */
342
+ function locateQuote(text, quote, occurrence) {
343
+ const wanted = String(quote ?? "");
344
+ if (!wanted.trim()) return { error: "quote the words to comment on" };
345
+ if (wanted.length > 2000) return { error: "the quoted text is too long; quote at most 2000 characters" };
346
+ if (/<!--|-->/.test(wanted)) return { error: "the quote may not contain HTML comment markers" };
347
+ const { plain, map } = visibleIndex(text);
348
+ const regions = forbiddenRegions(text);
349
+ const hits = [];
350
+ for (let at = plain.indexOf(wanted); at !== -1; at = plain.indexOf(wanted, at + 1)) {
351
+ const from = map[at];
352
+ const to = map[at + wanted.length - 1] + 1;
353
+ const blocked = regions.some(([start, end]) => from < end && to > start);
354
+ if (!blocked && !insideInlineCode(text, from)) hits.push({ from, to });
355
+ }
356
+ if (!hits.length) return { error: `"${wanted}" does not appear in the note's text (code blocks and frontmatter cannot be commented on)` };
357
+ if (occurrence === undefined && hits.length > 1) {
358
+ return { error: `"${wanted}" appears ${hits.length} times; pass occurrence (1 to ${hits.length}) to say which` };
359
+ }
360
+ const index = occurrence === undefined ? 1 : Number(occurrence);
361
+ if (!Number.isInteger(index) || index < 1 || index > hits.length) {
362
+ return { error: `occurrence must be between 1 and ${hits.length}` };
363
+ }
364
+ return hits[index - 1];
365
+ }
366
+
367
+ /**
368
+ * Start a thread: anchor `[from, to)` (or the located `quote`) and add the
369
+ * first comment. Returns `{ id, changes }` or `{ error }`.
370
+ */
371
+ function addThread(text, { quote, occurrence, from, to, author, body, at, id, random, point } = {}) {
372
+ const source = typeof text === "string" ? text : "";
373
+ if (!String(body ?? "").trim()) return { error: "a comment needs some text" };
374
+ let range;
375
+ if (Number.isInteger(from) && Number.isInteger(to)) {
376
+ // A point (the caret, no words) is allowed only when asked for: ⌘L at the
377
+ // cursor starts a thread where Tex will write, with nothing highlighted.
378
+ if (from < 0 || to > source.length || from > to || (from === to && point !== true)) return { error: "the selection is empty" };
379
+ const regions = forbiddenRegions(source);
380
+ if (regions.some(([start, end]) => from < end && to > start) || insideInlineCode(source, from)) {
381
+ return { error: "code blocks and frontmatter cannot be commented on" };
382
+ }
383
+ range = { from, to };
384
+ } else {
385
+ range = locateQuote(source, quote, occurrence);
386
+ if (range.error) return range;
387
+ }
388
+ const threadId = id && ID_RE.test(id) ? id : newThreadId(source, random);
389
+ const words = visibleIndex(source.slice(range.from, range.to)).plain;
390
+ const header = `${threadId} ${JSON.stringify(words.replace(/\s+/g, " ").trim().slice(0, 200))}`;
391
+ const entry = `${header}\n${eventLine({ at: isoNow(at), author, kind: "comment", text: body })}\n`;
392
+ const block = findBlock(source);
393
+ const changes = [
394
+ { from: range.from, to: range.from, insert: openMarker(threadId) },
395
+ { from: range.to, to: range.to, insert: closeMarker(threadId) },
396
+ ];
397
+ if (block) {
398
+ const parsed = parseComments(source);
399
+ const hasThreads = parsed.threads.length > 0;
400
+ changes.push({ from: block.bodyEnd, to: block.bodyEnd, insert: `${hasThreads ? "\n" : ""}${entry}` });
401
+ } else {
402
+ const trailing = source.endsWith("\n\n") ? "" : source.endsWith("\n") ? "\n" : source.length ? "\n\n" : "";
403
+ changes.push({ from: source.length, to: source.length, insert: `${trailing}\`\`\`comments\n${entry}\`\`\`\n` });
404
+ }
405
+ return { id: threadId, changes };
406
+ }
407
+
408
+ /**
409
+ * Add a reply, a resolve or a reopen to an existing thread. Returns
410
+ * `{ changes }` or `{ error }`. Resolving a resolved thread (or reopening an
411
+ * open one) is refused, so the log never records a change that changed nothing.
412
+ */
413
+ function appendEvent(text, { thread, kind, author, body, at } = {}) {
414
+ const source = typeof text === "string" ? text : "";
415
+ const found = parseComments(source).threads.find((t) => t.id === thread);
416
+ if (!found) return { error: `there is no comment thread "${thread}" on this note` };
417
+ if (!["comment", "resolved", "reopened", "suggestion", "kept", "undid"].includes(kind)) return { error: "unknown comment action" };
418
+ if ((kind === "kept" || kind === "undid") && !found.pending) return { error: `thread ${thread} has no suggested edit to ${kind === "kept" ? "keep" : "undo"}` };
419
+ if (kind === "comment" && !String(body ?? "").trim()) return { error: "a reply needs some text" };
420
+ if (kind === "resolved" && found.status === "resolved") return { error: `thread ${thread} is already resolved` };
421
+ if (kind === "reopened" && found.status === "open") return { error: `thread ${thread} is already open` };
422
+ const line = eventLine({ at: isoNow(at), author, kind, text: body });
423
+ const before = source.slice(0, found.end);
424
+ const insert = before.endsWith("\n") ? `${line}\n` : `\n${line}`;
425
+ return { changes: [{ from: found.end, to: found.end, insert }] };
426
+ }
427
+
428
+ /**
429
+ * Keep a thread's pending suggestion: its words replace the anchored words,
430
+ * and a `kept` line records who kept it. The markers stay where they were,
431
+ * so the thread still points at the (new) words. Any other thread's marker
432
+ * inside the replaced words is kept, moved to the end of the new words,
433
+ * rather than deleted with them, so no other comment comes loose.
434
+ */
435
+ function keepSuggestion(text, { thread, author, at } = {}) {
436
+ const source = typeof text === "string" ? text : "";
437
+ const parsed = parseComments(source);
438
+ const found = parsed.threads.find((t) => t.id === thread);
439
+ if (!found) return { error: `there is no comment thread "${thread}" on this note` };
440
+ if (!found.pending) return { error: `thread ${thread} has no suggested edit to keep` };
441
+ const anchor = parsed.anchors.get(thread);
442
+ if (!anchor) return { error: "the words this suggestion was for are gone" };
443
+ const kept = appendEvent(source, { thread, kind: "kept", author, at });
444
+ if (kept.error !== undefined) return kept;
445
+ const inner = source.slice(anchor.from, anchor.to);
446
+ const others = inner.match(MARKER_RE) ?? [];
447
+ return { changes: [{ from: anchor.from, to: anchor.to, insert: found.pending.text + others.join("") }, ...kept.changes] };
448
+ }
449
+
450
+ /**
451
+ * Delete one comment, or a whole thread.
452
+ *
453
+ * `index` counts the thread's comments (not its resolve and reopen lines) from
454
+ * 0. Deleting the first comment deletes the thread: its header, every line of
455
+ * its log, the blank line that separated it from its neighbour, and the two
456
+ * markers around its words, so the words themselves stay exactly as they were.
457
+ * The last thread takes the whole block with it. Deleting a reply removes that
458
+ * reply's lines and nothing else.
459
+ *
460
+ * This is the one edit here that removes rather than inserts. The log stays
461
+ * append-only for everything else, and a deletion is a person taking back what
462
+ * they (or, for an owner, anyone) wrote, which is what "delete" has to mean:
463
+ * a tombstone would leave the words in the file. `expect` (`{ at, author }`)
464
+ * is checked against the comment at `index`, so a thread that changed between
465
+ * the reader's click and the delete refuses rather than removing the wrong
466
+ * line.
467
+ */
468
+ function deleteComment(text, { thread, index, expect } = {}) {
469
+ const source = typeof text === "string" ? text : "";
470
+ const parsed = parseComments(source);
471
+ const found = parsed.threads.find((t) => t.id === thread);
472
+ if (!found) return { error: `there is no comment thread "${thread}" on this note` };
473
+ const said = found.events.filter((event) => event.kind === "comment");
474
+ const target = Number.isInteger(index) ? said[index] : undefined;
475
+ if (!target) return { error: `thread ${thread} has no comment ${index}` };
476
+ if (expect && (expect.at !== target.at || expect.author !== target.author)) {
477
+ return { error: "that comment changed while you were deleting it; try again" };
478
+ }
479
+ if (index > 0) return { changes: [{ from: target.start, to: target.end, insert: "" }] };
480
+
481
+ const changes = [];
482
+ const anchor = parsed.anchors.get(found.id);
483
+ if (anchor) {
484
+ changes.push({ from: anchor.openStart, to: anchor.from, insert: "" });
485
+ changes.push({ from: anchor.to, to: anchor.closeEnd, insert: "" });
486
+ }
487
+ const block = parsed.block;
488
+ if (parsed.threads.length === 1) {
489
+ // The only thread: the block goes, with the blank lines that led up to it,
490
+ // exactly as `stripComments` removes it.
491
+ let start = block.start;
492
+ while (start > 0 && source[start - 1] === "\n") start -= 1;
493
+ let end = block.end;
494
+ while (end < source.length && source[end] === "\n") end += 1;
495
+ const keep = start > 0 && end < source.length ? "\n\n" : start > 0 ? "\n" : "";
496
+ changes.push({ from: start, to: end, insert: keep });
497
+ return { changes };
498
+ }
499
+ let from = found.headerStart;
500
+ let to = found.end;
501
+ if (from - 2 >= block.bodyStart && source[from - 1] === "\n" && source[from - 2] === "\n") from -= 1;
502
+ else if (to < block.bodyEnd && source[to] === "\n") to += 1;
503
+ changes.push({ from, to, insert: "" });
504
+ return { changes };
505
+ }
506
+
507
+ /** Apply `{ from, to, insert }` changes (offsets in the original text). */
508
+ function applyChanges(text, changes) {
509
+ const sorted = [...changes].map((c, i) => ({ ...c, i })).sort((a, b) => b.from - a.from || b.i - a.i);
510
+ let out = text;
511
+ for (const change of sorted) out = out.slice(0, change.from) + change.insert + out.slice(change.to);
512
+ return out;
513
+ }
514
+
515
+ /**
516
+ * `text` without every closed fenced block carrying `info`.
517
+ *
518
+ * All of them, not the last one: `findBlock` answers the last because that is
519
+ * the one a new comment is appended to, and stripping borrowed it. They are
520
+ * not the same question. A note gets a second block from a paste, a
521
+ * hand-edit, or two writers each starting one where there was none, and a
522
+ * block left behind here is published word for word to everybody holding the
523
+ * link. Stripping is the side that must assume nothing.
524
+ */
525
+ function stripBlocks(text, info) {
526
+ let out = typeof text === "string" ? text : "";
527
+ for (;;) {
528
+ const blocks = fencedBlocks(out).filter((block) => block.info === info && block.closed);
529
+ const block = blocks.length ? blocks[blocks.length - 1] : null;
530
+ if (block === null) return out;
531
+ let start = block.start;
532
+ while (start > 0 && out[start - 1] === "\n") start -= 1;
533
+ const tail = out.slice(block.end);
534
+ out = out.slice(0, start) + (start > 0 ? "\n" : "") + tail.replace(/^\n+/, "");
535
+ }
536
+ }
537
+
538
+ /**
539
+ * The note without its comments: markers gone and every comments block
540
+ * removed. For every surface that publishes a note beyond its readers (share
541
+ * links, websites), where comments are never shown.
542
+ *
543
+ * The note's mail blocks (`mail.cjs`) go too: they are the same kind of
544
+ * conversation about the note rather than the note, and every caller here is
545
+ * a place they must not show. Found by info string here rather than through
546
+ * `mail.cjs`, which itself builds on this module.
547
+ */
548
+ function stripComments(text) {
549
+ return stripBlocks(stripBlocks(text, "comments"), "mail").replace(MARKER_RE, "");
550
+ }
551
+
552
+ /** One line for an agent: how many threads are open and on what. */
553
+ function describeComments(text) {
554
+ const { threads } = parseComments(text);
555
+ if (!threads.length) return null;
556
+ const open = threads.filter((t) => t.status === "open");
557
+ const resolved = threads.length - open.length;
558
+ const listed = open
559
+ .slice(0, 5)
560
+ .map((t) => `${t.id} on ${JSON.stringify(t.quote.length > 40 ? `${t.quote.slice(0, 39)}…` : t.quote)}${t.anchored ? "" : " (text deleted)"}`)
561
+ .join(", ");
562
+ return `${open.length} open${open.length ? ` (${listed}${open.length > 5 ? ", …" : ""})` : ""}, ${resolved} resolved`;
563
+ }
564
+
565
+ module.exports = {
566
+ COMMENTS_INFO: "comments",
567
+ MARKER_RE,
568
+ openMarker,
569
+ closeMarker,
570
+ findBlock,
571
+ findAnchors,
572
+ stripBlocks,
573
+ fencedBlocks,
574
+ lines,
575
+ parseComments,
576
+ sanitizeAuthor,
577
+ newThreadId,
578
+ locateQuote,
579
+ addThread,
580
+ appendEvent,
581
+ keepSuggestion,
582
+ deleteComment,
583
+ applyChanges,
584
+ stripComments,
585
+ describeComments,
586
+ };