beatrina 0.8.6 → 0.9.43

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 (112) hide show
  1. package/NOTICES +1 -1
  2. package/README.md +6 -0
  3. package/beatrina_V0.9.43.html +1885 -0
  4. package/beatrina_V0.9.43.html.inputs.json +1 -0
  5. package/bin/beatrina.mjs +156 -26
  6. package/bin/browser.mjs +31 -0
  7. package/bin/cli.mjs +64 -5
  8. package/bin/doctor-rows.mjs +31 -0
  9. package/bin/failsafe.mjs +8 -3
  10. package/bin/finder.mjs +74 -0
  11. package/bin/lsquery.swift +55 -0
  12. package/bin/pages.mjs +81 -0
  13. package/bin/python-setup.mjs +207 -0
  14. package/bin/runtime-dirs.mjs +27 -0
  15. package/bin/sessions.mjs +30 -10
  16. package/bin/shortcut.mjs +271 -35
  17. package/bin/update-check.mjs +2 -2
  18. package/build-info.json +1 -1
  19. package/engines/js/worker.mjs +6 -3
  20. package/engines/python/adapter.py +14 -13
  21. package/engines/python/analyze.py +4 -2
  22. package/engines/python/bootstrap.py +32 -31
  23. package/engines/python/debugger.py +10 -6
  24. package/engines/python/engine.json +1 -1
  25. package/engines/python/handoff.py +4 -2
  26. package/engines/python/worker.py +39 -10
  27. package/engines/r/engine.json +1 -1
  28. package/engines/r/handoff.R +4 -3
  29. package/failsafe/ai-policy.R +16 -16
  30. package/failsafe/ai-store.R +6 -6
  31. package/failsafe/cite.R +11 -11
  32. package/failsafe/journal.R +11 -11
  33. package/failsafe/plugins.R +27 -27
  34. package/failsafe/serve.R +364 -239
  35. package/failsafe/session-documents.R +104 -0
  36. package/host/ai-authority.mjs +55 -0
  37. package/host/ai-policy.mjs +48 -26
  38. package/host/bundle.mjs +194 -0
  39. package/host/deployment.mjs +25 -18
  40. package/host/engine-js.mjs +16 -17
  41. package/host/engine-pool.mjs +56 -8
  42. package/host/engine-python.mjs +80 -31
  43. package/host/engine-r.mjs +38 -32
  44. package/host/engine-stdio.mjs +45 -12
  45. package/host/env-names.mjs +148 -0
  46. package/host/gateway-token.mjs +51 -0
  47. package/host/journal-store.mjs +10 -9
  48. package/host/main.mjs +216 -76
  49. package/host/payload.mjs +131 -0
  50. package/host/planes/README.md +1 -1
  51. package/host/planes/ai-store.mjs +6 -5
  52. package/host/planes/ai.mjs +49 -29
  53. package/host/planes/analyze.mjs +6 -5
  54. package/host/planes/bundle.mjs +344 -0
  55. package/host/planes/choose.mjs +404 -0
  56. package/host/planes/cite.mjs +18 -17
  57. package/host/planes/files.mjs +0 -0
  58. package/host/planes/jobs.mjs +43 -20
  59. package/host/planes/latex.mjs +41 -5
  60. package/host/planes/mcp.mjs +80 -91
  61. package/host/planes/pair.mjs +24 -24
  62. package/host/planes/pipe-term.mjs +2 -2
  63. package/host/planes/plugins.mjs +1 -1
  64. package/host/planes/recent-documents.mjs +170 -0
  65. package/host/planes/sessions.mjs +230 -82
  66. package/host/planes/settings.mjs +4 -4
  67. package/host/planes/terminal.mjs +13 -11
  68. package/host/planes/test-file.mjs +2 -2
  69. package/host/planes/update.mjs +6 -13
  70. package/host/plugin-store.mjs +35 -52
  71. package/host/recent-documents.mjs +124 -0
  72. package/host/runtime-dir.mjs +47 -0
  73. package/host/server.mjs +123 -21
  74. package/host/session-keep.mjs +70 -0
  75. package/host/settings.mjs +85 -37
  76. package/host/update-record.mjs +3 -2
  77. package/host/user-dirs.mjs +60 -18
  78. package/host/which.mjs +39 -0
  79. package/host/windows-runtime.mjs +6 -3
  80. package/host/worker-plane.mjs +80 -7
  81. package/host/ws.mjs +9 -2
  82. package/host/zip.mjs +237 -0
  83. package/kernel/analyze.R +1 -1
  84. package/{check → kernel/check}/acceptance.mjs +1 -1
  85. package/kernel/check/knit-file.mjs +19639 -0
  86. package/{check → kernel/check}/session.mjs +49 -8
  87. package/kernel/deployment.R +20 -20
  88. package/kernel/examples/NOTICE.md +1 -1
  89. package/kernel/fileio.R +6 -6
  90. package/kernel/index.html +2 -2
  91. package/kernel/job-run.R +83 -22
  92. package/kernel/jobs.R +28 -12
  93. package/kernel/kernel-version +1 -1
  94. package/kernel/kernel.R +24 -21
  95. package/kernel/knitr-run.R +50 -9
  96. package/kernel/latex.R +429 -30
  97. package/kernel/mcp/{carmar-mcp.mjs → beatrina-mcp.mjs} +249 -59
  98. package/kernel/notebook-page.R +7 -7
  99. package/kernel/project.R +10 -10
  100. package/kernel/settings.R +105 -56
  101. package/kernel/sniff.R +4 -4
  102. package/kernel/typst.R +121 -0
  103. package/kernel/worker.R +602 -123
  104. package/kernel/workspace-keep.R +188 -0
  105. package/lib/agent-authoring-contract.js +28 -19
  106. package/lib/cell-kinds.js +3 -3
  107. package/lib/engine-labels.js +4 -4
  108. package/menu/Beatrina Menu.app/Contents/Info.plist +14 -0
  109. package/menu/Beatrina Menu.app/Contents/MacOS/Beatrina Menu +0 -0
  110. package/menu/Beatrina Menu.app/Contents/_CodeSignature/CodeResources +115 -0
  111. package/package.json +4 -3
  112. package/carmar_V0.8.6.html +0 -1310
package/kernel/latex.R CHANGED
@@ -1,6 +1,6 @@
1
1
  # latex.R — LaTeX compile decisions and diagnostics for the existing Jobs plane.
2
2
  # Used by the supervisor's job spec and the isolated job-run.R child.
3
- # Origin: carmar-latex-plugin/host/workbench.mjs compilerSpec and
3
+ # Origin: beatrina-latex-plugin/host/workbench.mjs compilerSpec and
4
4
  # parseCompilerDiagnostics; SHA-256 fd168f3c2a70d5f010542b8c080e9173d03cb4e8e40862e7d957731f2fee519b
5
5
  # Captured argv and observed log results: test/fixtures/latex/compiler.json.
6
6
  # These are prototype inputs to review, not a validated engine contract.
@@ -32,6 +32,7 @@
32
32
  LATEX_ENGINES <- c("tectonic", "latexmk", "pdflatex", "xelatex", "lualatex")
33
33
  LATEX_TIMEOUT <- 180L
34
34
  LATEX_DIAGNOSTIC_MAX <- 500L
35
+ LATEX_SOURCE_READ_MAX <- 4e6 # a source file consulted for a column
35
36
  LATEX_CITATION_MAX <- 100L
36
37
  # TeX's max_print_line: a log line of exactly this width has been hard-wrapped
37
38
  # and continues on the next line, with no marker (LEARNINGS 2026-09-07).
@@ -58,7 +59,7 @@ latex_compile <- function(target, engine, timeout, job_id, run_streaming, emit,
58
59
  # looks for it; it is replaced only by a successful run, atomically, so a
59
60
  # failed compile leaves the previous PDF exactly where it was.
60
61
  stem <- sub("\\.[^.]+$", "", basename(target))
61
- output <- file.path(dirname(target), ".carmar-latex", stem)
62
+ output <- file.path(dirname(target), ".beatrina-latex", stem)
62
63
  if (!dir.exists(output)) dir.create(output, recursive = TRUE, showWarnings = FALSE)
63
64
  if (!dir.exists(output)) stop("Cannot create the LaTeX build folder.", call. = FALSE)
64
65
  spec <- latex_argv(found$engine, target, output, fetch = fetch)
@@ -98,8 +99,12 @@ latex_compile <- function(target, engine, timeout, job_id, run_streaming, emit,
98
99
  # Parsed once and used twice: the pane gets the rows, and the failure
99
100
  # sentence gets to say what is in the pane rather than pointing at the log.
100
101
  diagnostics <- latex_log_diagnostics(diagnostic_lines, target)
102
+ # `engine`: which compiler said this. A FAILED compile emits no `output`
103
+ # frame, which was the only place the engine was named — so the one moment
104
+ # an explanation needs it ("this needs XeLaTeX", "Tectonic has no biber") was
105
+ # the moment it was unknown (docs/latex-ai-hardening-plan.md Stage 3).
101
106
  emit(list(type = "job", event = "diagnostics", rows = I(diagnostics),
102
- root = target, truncated = isTRUE(result$truncated)))
107
+ root = target, truncated = isTRUE(result$truncated), engine = found$engine))
103
108
  # What could be DONE about it, sent as a fact beside the rows rather than
104
109
  # left for the page to read out of the hint's prose. Emitted before either
105
110
  # `stop()` below, because the frame has to reach the browser whichever way
@@ -174,9 +179,9 @@ latex_options <- function(opts = list()) {
174
179
  # else — absent, "1", "yes", NA — is off. An option that means "reach the
175
180
  # network" must never be arrived at by coercion.
176
181
  fetch <- isTRUE(opts$fetch)
177
- c(CARMAR_LATEX_ENGINE = engine, CARMAR_LATEX_TIMEOUT = as.character(timeout),
178
- CARMAR_LATEX_FETCH = if (fetch) "1" else "",
179
- CARMAR_LATEX_IDENTITY = if (is.null(identity)) "" else jsonlite::toJSON(identity, auto_unbox = TRUE, digits = NA))
182
+ c(BEATRINA_LATEX_ENGINE = engine, BEATRINA_LATEX_TIMEOUT = as.character(timeout),
183
+ BEATRINA_LATEX_FETCH = if (fetch) "1" else "",
184
+ BEATRINA_LATEX_IDENTITY = if (is.null(identity)) "" else jsonlite::toJSON(identity, auto_unbox = TRUE, digits = NA))
180
185
  }
181
186
 
182
187
  #' Is this a usable executable file?
@@ -195,9 +200,9 @@ latex_discover <- function(engine = "auto", lookup = Sys.which, getenv = Sys.get
195
200
  engines <- if (engine == "auto") LATEX_ENGINES else engine
196
201
  result <- NULL
197
202
  Find(function(name) {
198
- override <- getenv(paste0("CARMAR_", toupper(name)))
203
+ override <- getenv(paste0("BEATRINA_", toupper(name)))
199
204
  if (nzchar(override)) {
200
- if (!usable(override)) stop(sprintf("CARMAR_%s does not name an executable file.", toupper(name)), call. = FALSE)
205
+ if (!usable(override)) stop(sprintf("BEATRINA_%s does not name an executable file.", toupper(name)), call. = FALSE)
201
206
  result <<- list(engine = name, binary = override)
202
207
  return(TRUE)
203
208
  }
@@ -209,7 +214,7 @@ latex_discover <- function(engine = "auto", lookup = Sys.which, getenv = Sys.get
209
214
  result <<- list(engine = name, binary = hit)
210
215
  TRUE
211
216
  }, engines)
212
- if (is.null(result)) stop(sprintf("%s was not found. Install a TeX engine or set its CARMAR_<ENGINE> binary path.",
217
+ if (is.null(result)) stop(sprintf("%s was not found. Install a TeX engine or set its BEATRINA_<ENGINE> binary path.",
213
218
  if (engine == "auto") "A LaTeX engine" else engine), call. = FALSE)
214
219
  result
215
220
  }
@@ -223,7 +228,7 @@ latex_discover <- function(engine = "auto", lookup = Sys.which, getenv = Sys.get
223
228
  #' instruction to go and use a terminal. That is a policy misapplied to its
224
229
  #' engine rather than a policy doing its job.
225
230
  #'
226
- #' So the promise is restated as the one CarmaR already keeps everywhere else
231
+ #' So the promise is restated as the one Beatrina already keeps everywhere else
227
232
  #' (spike/cite.R's style repository): the kernel reaches the network only when
228
233
  #' the person pressed something that said so. `fetch` is that press. It is
229
234
  #' never a default, never a setting, and never sticky — it is passed for ONE
@@ -265,7 +270,7 @@ latex_argv <- function(engine, target, output, fetch = FALSE) {
265
270
  #' The sentence a person can act on, for a missing asset under either engine.
266
271
  #'
267
272
  #' Tectonic and a local TeX fail the same way for different reasons, so this is
268
- #' the one place that difference is worded. CarmaR compiles offline by design
273
+ #' the one place that difference is worded. Beatrina compiles offline by design
269
274
  #' (`--only-cached`, so the kernel never touches the network), which means a
270
275
  #' Tectonic failure is almost always "not fetched yet" and the fix is one
271
276
  #' command; a local TeX failure is "not installed" and the fix is the
@@ -284,7 +289,7 @@ latex_missing_hint <- function(what, engine, target, plural = FALSE) {
284
289
  # There is one now (latex_argv's `fetch`, offered by the failure panel), so
285
290
  # the sentence points at what is on screen and keeps the command for
286
291
  # somebody who would rather, or whose page is not showing the panel.
287
- sprintf(paste0("%s %s not in Tectonic's package cache. CarmaR compiles offline, so nothing was ",
292
+ sprintf(paste0("%s %s not in Tectonic's package cache. Beatrina compiles offline, so nothing was ",
288
293
  "downloaded: use Fetch and compile below to get %s for one compile, or run ",
289
294
  "tectonic \"%s\" in a terminal (in %s)."),
290
295
  what, are, if (isTRUE(plural)) "them" else "it", basename(target), dirname(target))
@@ -294,7 +299,7 @@ latex_missing_hint <- function(what, engine, target, plural = FALSE) {
294
299
  }
295
300
  }
296
301
 
297
- #' What CarmaR could DO about this failure, as a fact rather than a sentence.
302
+ #' What Beatrina could DO about this failure, as a fact rather than a sentence.
298
303
  #'
299
304
  #' The hint below is prose for a person; this is the same reading of the same
300
305
  #' log for the PAGE, because a page that decides whether to offer a button by
@@ -303,7 +308,7 @@ latex_missing_hint <- function(what, engine, target, plural = FALSE) {
303
308
  #' split the export backends make over one parse tree.
304
309
  #'
305
310
  #' Only ONE fix is machine-actionable today: missing packages under Tectonic,
306
- #' which CarmaR can fetch for this compile. A local TeX distribution's missing
311
+ #' which Beatrina can fetch for this compile. A local TeX distribution's missing
307
312
  #' package is not — installing it is the distribution's business, not a button
308
313
  #' this program is entitled to press.
309
314
  #'
@@ -396,9 +401,13 @@ latex_failure_hint <- function(lines, engine, target, diagnostics = list()) {
396
401
  errors <- Filter(function(row) identical(row$severity, "error"), diagnostics)
397
402
  if (length(errors)) {
398
403
  first <- errors[[1L]]
399
- return(sprintf("%s in Problems; the first is %s line %d: %s",
404
+ # A diagnostic may legitimately carry no line (a summary the compiler did
405
+ # not place). `sprintf("%d", NA_integer_)` prints "line NA", so the file is
406
+ # named on its own instead.
407
+ where <- if (is.na(first$line)) basename(first$path) else sprintf("%s line %d", basename(first$path), first$line)
408
+ return(sprintf("%s in Problems; the first is %s: %s",
400
409
  if (length(errors) == 1L) "1 error is listed" else sprintf("%d errors are listed", length(errors)),
401
- basename(first$path), first$line, sub("[.]+$", "", first$message)))
410
+ where, sub("[.]+$", "", first$message)))
402
411
  }
403
412
  "See the compile log."
404
413
  }
@@ -407,9 +416,73 @@ latex_failure_hint <- function(lines, engine, target, diagnostics = list()) {
407
416
  #' @param lines Compiler stdout or log lines.
408
417
  #' @param root Absolute root source path.
409
418
  #' @return Bounded diagnostic records; browser conversion owns UTF-16 offsets.
419
+ #' Severity of a compiler message.
420
+ #'
421
+ #' The engine's own `error:`/`warning:` prefix is authoritative when present.
422
+ #' Without one, only a LEADING LaTeX warning marker counts — an error whose text
423
+ #' merely contains the word "warning" is still an error, and `grepl("warning",
424
+ #' message)` made one of those a warning.
425
+ #' @param prefix The `error`/`warning` token the engine printed, or "".
426
+ #' @param message The message text.
427
+ #' @return `"warning"` or `"error"`.
428
+ latex_severity <- function(prefix, message) {
429
+ prefix <- tolower(trimws(paste0(prefix, "")))
430
+ if (identical(prefix, "warning")) return("warning")
431
+ if (identical(prefix, "error")) return("error")
432
+ if (grepl("^(?:LaTeX|Package[^:]*|Class[^:]*|pdfTeX|Font)[[:space:]]+[Ww]arning:", paste0(message, ""), perl = TRUE)) "warning" else "error"
433
+ }
434
+
435
+ #' The 1-based CODE POINT column an `l.N` echo points at, or NA.
436
+ #'
437
+ #' TeX prints the text it had consumed when it stopped:
438
+ #'
439
+ #' l.4 \\undefinedcontrolsequence
440
+ #' <- the remainder, padded into place
441
+ #'
442
+ #' The obvious move is to measure that echo, and it is wrong: the echo is LOSSY.
443
+ #' Measured against a real tectonic 0.15.0 log, a source `\U1D538` (one code
444
+ #' point, two UTF-16 units) is written to the log as `\UD538`, one unit — so a
445
+ #' column counted in the echo is short by one unit per astral character and
446
+ #' lands inside a surrogate pair.
447
+ #'
448
+ #' So the echo is only ever a HINT, and a column is returned only when the hint
449
+ #' is an EXACT prefix of the genuine source line. When TeX wrapped the echo, or
450
+ #' mangled a character, or the file cannot be read, the answer is NA — which is
451
+ #' what this function returned for every input before it existed, and remains
452
+ #' the honest answer. A column that cannot be justified is worse than none.
453
+ #' @param echo The text after `l.N `.
454
+ #' @param source_line The genuine line, or NA.
455
+ #' @return A 1-based code-point column, or `NA_integer_`.
456
+ latex_echo_column <- function(echo, source_line) {
457
+ if (!latex_scalar(echo) || !nzchar(echo) || !latex_scalar(source_line)) return(NA_integer_)
458
+ if (!startsWith(source_line, echo)) return(NA_integer_)
459
+ nchar(echo, type = "chars") + 1L
460
+ }
461
+
410
462
  latex_log_diagnostics <- function(lines, root) {
411
463
  stopifnot(is.character(lines), latex_scalar(root))
412
464
  rows <- list(); seen <- character(); pending <- NULL; stack <- list()
465
+ # Scoped to THIS call on purpose: a cache outliving one compile would compute
466
+ # a column from the text as it was before the edit that triggered the rebuild.
467
+ source_cache <- new.env(parent = emptyenv())
468
+ source_line <- function(path, line) {
469
+ if (!is.finite(line) || line < 1L) return(NA_character_)
470
+ if (is.null(source_cache[[path]])) {
471
+ # Unreadable, absent, oversized or binary: no column. This is the
472
+ # documented safe outcome, not a swallowed failure — the diagnostic is
473
+ # still reported, with its line and without a column.
474
+ value <- if (file.exists(path) && !dir.exists(path) && file.size(path) <= LATEX_SOURCE_READ_MAX) {
475
+ tryCatch({
476
+ text <- readLines(path, warn = FALSE)
477
+ Encoding(text) <- "UTF-8"
478
+ text
479
+ }, error = function(e) character())
480
+ } else character()
481
+ assign(path, value, envir = source_cache)
482
+ }
483
+ text <- source_cache[[path]]
484
+ if (line > length(text)) NA_character_ else text[[line]]
485
+ }
413
486
  current <- function() {
414
487
  files <- Filter(function(value) !is.null(value) && nzchar(value), stack)
415
488
  if (length(files)) files[[length(files)]] else root
@@ -420,32 +493,57 @@ latex_log_diagnostics <- function(lines, root) {
420
493
  if (!file.exists(file) && file.exists(paste0(file, ".tex"))) file <- paste0(file, ".tex")
421
494
  normalizePath(file, mustWork = FALSE)
422
495
  }
423
- add <- function(file, line, message, severity = "error", col = NA_integer_) {
496
+ # The log lines AROUND a finding, bounded: the message names the error, but
497
+ # TeX says what it was reading (`l.12 \badcommand`) and what it did about it
498
+ # on the lines that follow, and that is the evidence an explanation needs.
499
+ # `from`..`to` are indices into `lines`; at most 8 lines and 600 characters,
500
+ # so 200 rows cannot turn a frame into the log.
501
+ excerpt <- function(from, to) {
502
+ if (is.na(from) || is.na(to)) return("")
503
+ span <- lines[seq.int(max(1L, from), min(length(lines), max(from, to)))]
504
+ span <- utils::head(span[nzchar(trimws(span))], 8L)
505
+ substr(paste(span, collapse = "\n"), 1L, 600L)
506
+ }
507
+ add <- function(file, line, message, severity = "error", col = NA_integer_,
508
+ from = NA_integer_, to = NA_integer_) {
424
509
  file <- resolve_file(file)
425
510
  key <- paste(file, line, col, sub("[.]+$", "", trimws(message)), sep = "\r")
426
511
  if (!key %in% seen && length(rows) < LATEX_DIAGNOSTIC_MAX) {
427
512
  seen <<- c(seen, key)
428
513
  rows[[length(rows) + 1L]] <<- list(path = file, line = as.integer(line), col = col,
429
- message = trimws(message), severity = severity, source = "LaTeX compiler")
514
+ message = trimws(message), severity = severity, source = "LaTeX compiler",
515
+ log = excerpt(from, to))
430
516
  }
431
517
  }
432
- lapply(lines, function(line) {
518
+ lapply(seq_along(lines), function(i) {
519
+ line <- lines[[i]]
433
520
  # file-line-error and Tectonic include the file explicitly, including drives.
434
521
  hit <- regmatches(line, regexec("^(?:(error|warning):[[:space:]]*)?(.+?):([0-9]+):(?:([0-9]+):)?[[:space:]]*(.+)$", line, perl = TRUE))[[1L]]
435
522
  if (length(hit) && (nzchar(hit[[2]]) || grepl("\\.(tex|sty|cls|bib)$", hit[[3]]) || file.exists(resolve_file(hit[[3]])))) {
436
- add(hit[[3]], as.integer(hit[[4]]), hit[[6]], if (grepl("warning", paste(hit[[2]], hit[[6]]), ignore.case = TRUE)) "warning" else "error",
437
- if (nzchar(hit[[5]])) as.integer(hit[[5]]) else NA_integer_)
523
+ add(hit[[3]], as.integer(hit[[4]]), hit[[6]], latex_severity(hit[[2]], hit[[6]]),
524
+ if (nzchar(hit[[5]])) as.integer(hit[[5]]) else NA_integer_, from = i, to = i + 4L)
438
525
  pending <<- NULL; return(NULL)
439
526
  }
440
- if (startsWith(line, "!")) { pending <<- list(file = current(), message = trimws(sub("^!", "", line))); return(NULL) }
441
- location <- regmatches(line, regexec("^l\\.([0-9]+)[[:space:]]", line, perl = TRUE))[[1L]]
527
+ if (startsWith(line, "!")) { pending <<- list(file = current(), message = trimws(sub("^!", "", line)), at = i); return(NULL) }
528
+ location <- regmatches(line, regexec("^l\\.([0-9]+)[[:space:]](.*)$", line, perl = TRUE))[[1L]]
442
529
  if (length(location) && !is.null(pending)) {
443
- add(pending$file, as.integer(location[[2]]), pending$message); pending <<- NULL; return(NULL)
530
+ at_line <- as.integer(location[[2]])
531
+ # The echo is a hint; the genuine source line is the authority. NA unless
532
+ # the two agree exactly — see latex_echo_column().
533
+ col <- latex_echo_column(location[[3]], source_line(resolve_file(pending$file), at_line))
534
+ add(pending$file, at_line, pending$message, col = col, from = pending$at, to = i + 2L)
535
+ pending <<- NULL; return(NULL)
444
536
  }
445
537
  warning <- regmatches(line, regexec("(?:LaTeX|Package .+) Warning: (.+?)(?: on input line ([0-9]+))?\\.?$", line, perl = TRUE))[[1L]]
446
- if (length(warning)) { add(current(), if (nzchar(warning[[3]])) as.integer(warning[[3]]) else 1L, warning[[2]], "warning"); return(NULL) }
538
+ # A message with no `on input line` has NO line, and saying 1 is inventing
539
+ # one. "LaTeX Warning: There were undefined references." is about the
540
+ # document, not about its first line, and a reader sent to line 1 has been
541
+ # sent somewhere the compiler never pointed. NA travels as a file-level
542
+ # diagnostic (lib/latex-diagnostics.js anchors it at the top of the file and
543
+ # marks it `fileLevel`), so nothing is lost and nothing is claimed.
544
+ if (length(warning)) { add(current(), if (nzchar(warning[[3]])) as.integer(warning[[3]]) else NA_integer_, warning[[2]], "warning"); return(NULL) }
447
545
  if (grepl("^error:", line) && !grepl("^error: (halted on|unexpectedly halted)", line)) {
448
- add(current(), 1L, sub("^error:[[:space:]]*", "", line)); return(NULL)
546
+ add(current(), NA_integer_, sub("^error:[[:space:]]*", "", line)); return(NULL)
449
547
  }
450
548
  # Track log parentheses, including anonymous parentheses, so a closing
451
549
  # package group returns !/l.N diagnostics to the including source.
@@ -603,7 +701,308 @@ latex_citation_problems <- function(tex_lines, bib_lines, engine, fetch = FALSE)
603
701
 
604
702
  # ── the rapid preview ──────────────────────────────────────────────────────
605
703
  #
606
- # The live preview (a .tex through pandoc to HTML while you type) is answered by
607
- # the supervisor, host/planes/latex.mjs. It lived here while the R supervisor
608
- # did; it was retired with serve.R (docs/host-plan.md §13), and nothing in this
609
- # file's compile half used it.
704
+ # A .tex through pandoc to HTML, fast enough to keep up with typing. This is
705
+ # the "live rich preview" of the retired prototype (spike/latex-editor.html +
706
+ # spike/latex-workbench.mjs, harvested and deleted 2026-09-06), which was
707
+ # scoped here as WP5 in docs/latex-plan.md and cut for byte budget before it
708
+ # was built. The argv is the prototype's, unchanged, because it was already
709
+ # right; what is new is where it runs and what it is allowed to touch.
710
+ #
711
+ # IT IS NOT A COMPILE, and every difference follows from that. A compile is a
712
+ # JOB — detached, streamed, minutes long, and it produces the artefact you
713
+ # publish. This answers one request in under a second and produces something
714
+ # to look at while you write. So it is answered in the supervisor beside
715
+ # `cite` rather than spawned as a job child: a job that outlives the keystroke
716
+ # that asked for it is exactly what must not happen here.
717
+ #
718
+ # WHAT IT MAY READ is the root's own directory and below, and nothing else.
719
+ # TeX itself reads relative to the document, so that bound is the document's
720
+ # own, not an invention — and it is checked after canonicalisation, because a
721
+ # string-prefix test on an unresolved path is how confinement bugs happen
722
+ # (spike/worker.R within_root says the same thing about the same mistake).
723
+
724
+ LATEX_PREVIEW_TIMEOUT_MS <- 8000L
725
+ LATEX_PREVIEW_MAX_SOURCE <- 2e6 # the .tex the page sends
726
+ LATEX_PREVIEW_MAX_HTML <- 6e6 # what pandoc may print back
727
+ LATEX_PREVIEW_MAX_IMAGE <- 1.5e6 # one figure, before base64
728
+ LATEX_PREVIEW_MAX_ASSETS <- 8e6 # every figure together
729
+ LATEX_PREVIEW_MAX_FILES <- 40L # buffers, and includes followed
730
+ LATEX_PREVIEW_DEPTH <- 6L
731
+
732
+ # What an <img> can actually show. A .pdf or .eps figure is normal in a real
733
+ # paper and cannot be inlined, so it is REPORTED rather than dropped — the
734
+ # pane says "3 figures are only in the PDF", which is true and actionable,
735
+ # where a blank space says nothing.
736
+ LATEX_PREVIEW_IMAGE_TYPES <- c(png = "image/png", jpg = "image/jpeg",
737
+ jpeg = "image/jpeg", gif = "image/gif",
738
+ svg = "image/svg+xml", webp = "image/webp")
739
+
740
+ #' Is `path` inside `dir`, after both are canonicalised?
741
+ #'
742
+ #' The trailing separator is load-bearing: without it, /p/figs would also
743
+ #' admit /p/figs-private. Mirrors plugin_contained() in spike/plugins.R.
744
+ #' @param dir Directory that bounds the read.
745
+ #' @param path Candidate file.
746
+ #' @return The resolved path, or "" when it is outside or absent.
747
+ latex_within <- function(dir, path) {
748
+ if (!latex_scalar(dir) || !latex_scalar(path) || !dir.exists(dir)) return("")
749
+ root <- normalizePath(dir, winslash = "/", mustWork = TRUE)
750
+ full <- if (grepl("^([A-Za-z]:)?[/\\\\]", path)) path else file.path(root, path)
751
+ if (!file.exists(full)) return("")
752
+ full <- normalizePath(full, winslash = "/", mustWork = TRUE)
753
+ if (!identical(full, root) && !startsWith(full, paste0(root, "/"))) return("")
754
+ full
755
+ }
756
+
757
+ #' Pull `\input`/`\include`/`\subfile` bodies into one source, so the preview
758
+ #' shows the whole paper rather than its first chapter.
759
+ #'
760
+ #' Buffers the page sent win over the disk copy, because the point of a live
761
+ #' preview is UNSAVED text. Bounded by depth and by file count, and a file
762
+ #' already on the stack is skipped rather than followed — an include cycle is
763
+ #' a document someone is halfway through writing, not an attack, and it must
764
+ #' cost a stack frame instead of the session.
765
+ #' @param source The root's text.
766
+ #' @param dir Directory the root lives in.
767
+ #' @param buffers Named list of relative path -> text, from open editors.
768
+ #' @param seen Paths already on this branch.
769
+ #' @param depth Remaining depth.
770
+ #' @return One string.
771
+ latex_preview_expand <- function(source, dir, buffers = list(), seen = character(0), depth = LATEX_PREVIEW_DEPTH) {
772
+ if (depth <= 0L) return(source)
773
+ pattern <- "\\\\(?:input|include|subfile)\\{([^{}]{1,200})\\}"
774
+ m <- gregexpr(pattern, source, perl = TRUE)[[1L]]
775
+ if (identical(as.integer(m[1L]), -1L)) return(source)
776
+ starts <- as.integer(m)
777
+ lens <- attr(m, "match.length")
778
+ out <- character(0)
779
+ at <- 1L
780
+ for (i in seq_along(starts)) { # one splice per include
781
+ whole <- substr(source, starts[i], starts[i] + lens[i] - 1L)
782
+ rel <- sub(pattern, "\\1", whole, perl = TRUE)
783
+ if (!grepl("\\.[A-Za-z0-9]{1,5}$", rel)) rel <- paste0(rel, ".tex")
784
+ body <- NULL
785
+ if (!rel %in% seen && length(seen) < LATEX_PREVIEW_MAX_FILES) {
786
+ if (!is.null(buffers[[rel]])) body <- buffers[[rel]]
787
+ else {
788
+ hit <- latex_within(dir, rel)
789
+ if (nzchar(hit) && file.info(hit)$size <= LATEX_PREVIEW_MAX_SOURCE) {
790
+ body <- tryCatch(paste(readLines(hit, warn = FALSE), collapse = "\n"),
791
+ error = function(e) NULL)
792
+ }
793
+ }
794
+ }
795
+ out <- c(out, substr(source, at, starts[i] - 1L),
796
+ if (is.null(body)) "" else
797
+ latex_preview_expand(body, dir, buffers, c(seen, rel), depth - 1L))
798
+ at <- starts[i] + lens[i]
799
+ }
800
+ paste0(paste(out, collapse = ""), substr(source, at, nchar(source)))
801
+ }
802
+
803
+ #' The .bib files a source names, resolved and bounded.
804
+ #' @param source Expanded LaTeX.
805
+ #' @param dir Directory that bounds the read.
806
+ #' @return Character vector of absolute paths, possibly empty.
807
+ latex_preview_bibliography <- function(source, dir) {
808
+ m <- regmatches(source, gregexpr("\\\\(?:bibliography|addbibresource)(?:\\[[^]]*\\])?\\{([^{}]{1,300})\\}",
809
+ source, perl = TRUE))[[1L]]
810
+ if (!length(m)) return(character(0))
811
+ named <- unlist(lapply(m, function(one) {
812
+ inner <- sub(".*\\{([^{}]*)\\}$", "\\1", one)
813
+ trimws(strsplit(inner, ",", fixed = TRUE)[[1L]])
814
+ }), use.names = FALSE)
815
+ named <- named[nzchar(named)]
816
+ named <- ifelse(grepl("\\.[A-Za-z0-9]{1,5}$", named), named, paste0(named, ".bib"))
817
+ found <- vapply(unique(named), function(one) latex_within(dir, one), character(1))
818
+ unname(found[nzchar(found)])
819
+ }
820
+
821
+ #' Turn every local `<img src>` into a data: URI.
822
+ #'
823
+ #' The kernel does this itself, over the HTML IT just produced, so no image
824
+ #' path ever travels on the wire in either direction — the same rule `job_open`
825
+ #' follows when it names a job rather than a file. `readfile` could not have
826
+ #' served here at all: it decodes bytes as UTF-8 or Latin-1 (spike/worker.R
827
+ #' text_from_bytes), so a PNG through it is not a PNG.
828
+ #' @param html pandoc's output.
829
+ #' @param dir Directory that bounds the read.
830
+ #' @return list(html, inlined, dropped) — dropped names what could not be shown.
831
+ latex_preview_inline <- function(html, dir) {
832
+ hits <- gregexpr('src="([^"]{1,400})"', html, perl = TRUE)[[1L]]
833
+ if (identical(as.integer(hits[1L]), -1L)) return(list(html = html, inlined = 0L, dropped = character(0)))
834
+ starts <- as.integer(hits)
835
+ lens <- attr(hits, "match.length")
836
+ out <- character(0)
837
+ at <- 1L
838
+ inlined <- 0L
839
+ budget <- LATEX_PREVIEW_MAX_ASSETS
840
+ dropped <- character(0)
841
+ for (i in seq_along(starts)) { # one rewrite per image
842
+ whole <- substr(html, starts[i], starts[i] + lens[i] - 1L)
843
+ src <- sub('^src="(.*)"$', "\\1", whole)
844
+ replacement <- whole
845
+ if (!grepl("^(?:data:|https?:|//)", src, perl = TRUE)) {
846
+ ext <- tolower(sub(".*\\.([A-Za-z0-9]+)$", "\\1", src))
847
+ mime <- unname(LATEX_PREVIEW_IMAGE_TYPES[ext])
848
+ # A figure named without its extension is what \includegraphics{fig}
849
+ # writes, and TeX picks the file. Try the types an <img> can show, in
850
+ # the order a person would expect them to win.
851
+ candidates <- if (identical(src, ext) || is.na(mime))
852
+ paste0(sub("\\.[A-Za-z0-9]+$", "", src), ".", names(LATEX_PREVIEW_IMAGE_TYPES)) else src
853
+ hit <- ""
854
+ for (cand in candidates) { # first existing wins
855
+ hit <- latex_within(dir, cand)
856
+ if (nzchar(hit)) { mime <- unname(LATEX_PREVIEW_IMAGE_TYPES[tolower(sub(".*\\.([A-Za-z0-9]+)$", "\\1", cand))]); break }
857
+ }
858
+ if (!nzchar(hit) || is.na(mime)) dropped <- c(dropped, basename(src))
859
+ else {
860
+ size <- file.info(hit)$size
861
+ if (!is.finite(size) || size > LATEX_PREVIEW_MAX_IMAGE || size > budget) {
862
+ dropped <- c(dropped, basename(src))
863
+ } else {
864
+ bytes <- tryCatch(readBin(hit, "raw", n = size), error = function(e) NULL)
865
+ if (is.null(bytes)) dropped <- c(dropped, basename(src))
866
+ else {
867
+ budget <- budget - size
868
+ inlined <- inlined + 1L
869
+ replacement <- paste0('src="data:', mime, ';base64,', jsonlite::base64_enc(bytes), '"')
870
+ }
871
+ }
872
+ }
873
+ }
874
+ out <- c(out, substr(html, at, starts[i] - 1L), replacement)
875
+ at <- starts[i] + lens[i]
876
+ }
877
+ list(html = paste0(paste(out, collapse = ""), substr(html, at, nchar(html))),
878
+ inlined = inlined, dropped = unique(dropped))
879
+ }
880
+
881
+ #' Highlighted code blocks as plain verbatim, for the PREVIEW only.
882
+ #'
883
+ #' The LaTeX export writes R chunks as fancyvrb `Highlighting` blocks
884
+ #' (lib/md/latex.js `highlighted`) — correct for a TeX engine, but pandoc's
885
+ #' LaTeX reader does not know `\DefineVerbatimEnvironment{Highlighting}` is
886
+ #' verbatim and renders each block as an EMPTY div, so the preview showed a
887
+ #' document with its code missing while the PDF was right (found by the
888
+ #' Beatrix fork, 2026-09-15). Each block is rewritten to `\begin{verbatim}`
889
+ #' with the token macros dropped and lib/md/latex.js CODE_CH undone. The file
890
+ #' on disk and the compile are untouched.
891
+ #'
892
+ #' Escapes become sentinels BEFORE the macro braces are stripped, so a literal
893
+ #' `{` in the code survives. A code line holding `\end{verbatim}` would close
894
+ #' the environment early; it gains a zero-width space after the backslash,
895
+ #' invisible in the preview.
896
+ #'
897
+ #' @param source LaTeX text.
898
+ #' @return The text with every Shaded/Highlighting block replaced.
899
+ latex_preview_code <- function(source) {
900
+ pattern <- paste0("(?s)(?:\\\\begin\\{Shaded\\}[ \\t]*\\n?)?",
901
+ "\\\\begin\\{Highlighting\\}(?:\\[[^]\\n]*\\])?\\n?(.*?)\\n?",
902
+ "\\\\end\\{Highlighting\\}(?:[ \\t]*\\n?\\\\end\\{Shaded\\})?")
903
+ hits <- gregexpr(pattern, source, perl = TRUE)[[1L]]
904
+ if (identical(as.integer(hits[1L]), -1L)) return(source)
905
+ blocks <- regmatches(source, list(hits))[[1L]]
906
+ # Order matters only for \textbackslash{}, whose braces must not be read as
907
+ # a {-} or stripped first; every other entry is a distinct sequence.
908
+ swaps <- c("\\textbackslash{}" = "\001", "\\textasciitilde{}" = "~", "\\^{}" = "^",
909
+ "\\textless{}" = "<", "\\textgreater{}" = ">", "{-}" = "-",
910
+ "\\{" = "\002", "\\}" = "\003", "\\#" = "#", "\\%" = "%",
911
+ "\\_" = "_", "\\&" = "&")
912
+ plain <- vapply(blocks, function(block) {
913
+ body <- sub(pattern, "\\1", block, perl = TRUE)
914
+ body <- Reduce(function(text, from) gsub(from, swaps[[from]], text, fixed = TRUE),
915
+ names(swaps), body)
916
+ body <- gsub("\\\\[A-Za-z]+Tok\\{", "", body, perl = TRUE)
917
+ body <- gsub("[{}]", "", body, perl = TRUE)
918
+ body <- chartr("\001\002\003", "\\{}", body)
919
+ body <- gsub("\\end{verbatim}", "\\\u200bend{verbatim}", body, fixed = TRUE)
920
+ paste0("\\begin{verbatim}\n", body, "\n\\end{verbatim}")
921
+ }, character(1), USE.NAMES = FALSE)
922
+ regmatches(source, list(hits)) <- list(plain)
923
+ source
924
+ }
925
+
926
+ #' Render one LaTeX source to HTML for the preview pane.
927
+ #'
928
+ #' @param source The root's text, as the editor holds it.
929
+ #' @param path Absolute path of the root, for resolving its neighbours.
930
+ #' @param buffers Optional named list of relative path -> unsaved text.
931
+ #' @param timeout_ms Deadline.
932
+ #' @return list(ok, html, warnings, elapsed_ms, inlined, dropped) or
933
+ #' list(ok = FALSE, error).
934
+ latex_preview <- function(source, path, buffers = list(), timeout_ms = LATEX_PREVIEW_TIMEOUT_MS) {
935
+ if (!latex_scalar(source)) return(list(ok = FALSE, error = "No LaTeX source to preview."))
936
+ if (nchar(source, type = "bytes") > LATEX_PREVIEW_MAX_SOURCE) {
937
+ return(list(ok = FALSE, error = "This document is too large to preview while you type."))
938
+ }
939
+ bin <- find_pandoc()
940
+ if (!nzchar(bin)) {
941
+ return(list(ok = FALSE, error = "pandoc is not installed, or Beatrina could not find it. Compile still works; only the live preview needs pandoc."))
942
+ }
943
+ dir <- if (latex_scalar(path) && file.exists(path)) dirname(normalizePath(path, winslash = "/", mustWork = TRUE)) else ""
944
+ keep <- list()
945
+ if (is.list(buffers)) {
946
+ names_ok <- names(buffers) %||% character(0)
947
+ for (nm in utils::head(names_ok[nzchar(names_ok)], LATEX_PREVIEW_MAX_FILES)) {
948
+ if (latex_scalar(buffers[[nm]])) keep[[nm]] <- buffers[[nm]]
949
+ }
950
+ }
951
+ expanded <- if (nzchar(dir)) latex_preview_expand(source, dir, keep) else source
952
+ expanded <- latex_preview_code(expanded)
953
+ started <- Sys.time()
954
+ args <- c("--from=latex", "--to=html5", "--mathml", "--wrap=none",
955
+ "--standalone", "--sandbox")
956
+ if (nzchar(dir)) {
957
+ for (bib in latex_preview_bibliography(expanded, dir)) {
958
+ args <- c(args, "--citeproc", paste0("--bibliography=", bib))
959
+ }
960
+ }
961
+ # A FILE, not stdin: processx::run has no `input` argument (it takes a path
962
+ # for `stdin`), and cite_run already writes its document to a 0600 temp file
963
+ # for the same reason. pandoc emits the figure paths unchanged either way —
964
+ # this function resolves them itself, against the ROOT's directory rather
965
+ # than the scratch one, which is what makes the temp file harmless here.
966
+ input <- tempfile("beatrina-preview-", fileext = ".tex")
967
+ on.exit(unlink(input), add = TRUE)
968
+ writeLines(expanded, input, useBytes = TRUE)
969
+ Sys.chmod(input, "0600")
970
+ ran <- tryCatch(processx::run(
971
+ bin, c(args, input), timeout = timeout_ms / 1000, error_on_status = FALSE,
972
+ echo = FALSE, cleanup_tree = TRUE,
973
+ # HOME and the data dir moved aside for the same reason cite_run moves
974
+ # them: a render must not read or write this user's pandoc configuration.
975
+ env = c("current", PANDOC_DATA_DIR = tempdir(), HOME = tempdir())
976
+ ), error = function(e) e)
977
+ if (inherits(ran, "error")) {
978
+ msg <- conditionMessage(ran)
979
+ return(list(ok = FALSE, error = if (grepl("timeout", msg, ignore.case = TRUE))
980
+ "The preview took too long and was stopped." else paste0("preview: ", msg)))
981
+ }
982
+ if (isTRUE(ran$timeout)) return(list(ok = FALSE, error = "The preview took too long and was stopped."))
983
+ if (!identical(as.integer(ran$status), 0L)) {
984
+ first <- strsplit(ran$stderr %||% "", "\n", fixed = TRUE)[[1L]][1L] %||% ""
985
+ # pandoc names the file it was reading, and that file is our scratch copy.
986
+ # Printing "/var/folders/.../beatrina-preview-8b42.tex (line 2, column 2)"
987
+ # at a person tells them nothing and looks like a fault in Beatrina; the
988
+ # line and column are the useful half, so the path becomes the document's
989
+ # own name. An unclosed group is the ORDINARY state of a document being
990
+ # typed, which is why this path is a reported note and not a failure —
991
+ # lib/latex-preview.js keeps the last good render behind it.
992
+ shown <- if (latex_scalar(path) && nzchar(path)) basename(path) else "the document"
993
+ first <- gsub(input, shown, first, fixed = TRUE)
994
+ return(list(ok = FALSE, partial = TRUE,
995
+ error = paste0("pandoc could not read this document",
996
+ if (nzchar(first)) paste0(": ", first) else ".")))
997
+ }
998
+ html <- ran$stdout %||% ""
999
+ if (nchar(html, type = "bytes") > LATEX_PREVIEW_MAX_HTML) {
1000
+ return(list(ok = FALSE, error = "The rendered preview is too large to show."))
1001
+ }
1002
+ figures <- if (nzchar(dir)) latex_preview_inline(html, dir)
1003
+ else list(html = html, inlined = 0L, dropped = character(0))
1004
+ list(ok = TRUE, html = figures$html,
1005
+ warnings = trimws(ran$stderr %||% ""),
1006
+ elapsed_ms = as.numeric(difftime(Sys.time(), started, units = "secs")) * 1000,
1007
+ inlined = figures$inlined, dropped = figures$dropped)
1008
+ }