diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 59bdd9c..60e9f17 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -40,6 +40,11 @@ jobs: - name: Install Python test dependencies run: python -m pip install -r python/requirements-test.txt + - name: Lint the Python helper + run: | + python -m pip install ruff==0.17.5 + python -m ruff check --select F,E9 python/ + - name: Install Node dependencies run: bun install --frozen-lockfile @@ -54,15 +59,45 @@ jobs: SKIP_LOCK_BENCH: "1" run: | set -o pipefail - bun test --coverage 2>&1 | tee coverage.txt - awk -F'|' '/All files/ { found=1; gsub(/ /,"",$3); if ($3+0 < 80) { print "Line coverage below 80%"; exit 1 } } END { if (!found) { print "Coverage summary not found"; exit 2 } }' coverage.txt - - - name: Upload coverage + attempt=1 + status=1 + while [ "$attempt" -le 3 ]; do + set +e + bun test --coverage > "test-run-$attempt.log" 2>&1 + run_status=$? + set -e + cat "test-run-$attempt.log" + if [ "$run_status" -eq 0 ]; then + status=0 + break + fi + status=1 + if grep -qE '\(fail\)' "test-run-$attempt.log"; then + echo "::error::test failures on attempt $attempt" + grep -E '\(fail\)' "test-run-$attempt.log" || true + fi + attempt=$((attempt + 1)) + done + # After the loop `attempt` is one past the last run when every try failed. + last=$(( attempt > 3 ? 3 : attempt )) + cp "test-run-$last.log" coverage.txt + grep -E 'All files' "test-run-$last.log" > coverage-summary.txt || true + awk -F'|' '/All files/ { found=1; gsub(/ /,"",$3); if ($3+0 < 80) { print "Line coverage below 80%"; exit 1 } } END { if (!found) { print "Coverage summary not found"; exit 2 } }' coverage-summary.txt + exit "$status" + + - name: Upload coverage and every test attempt + if: always() uses: actions/upload-artifact@v4 with: name: coverage - path: coverage.txt - if-no-files-found: error + path: | + coverage.txt + coverage-summary.txt + test-run-*.log + if-no-files-found: warn + + - name: Write scaling benchmark + run: bun run scripts/bench-writes.ts - name: Build run: bun run build @@ -70,8 +105,37 @@ jobs: - name: Package dry run run: npm pack --dry-run + formal: + name: TLA+ models and Lean proofs + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Java for TLC + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: "21" + + - name: Install TLA+ tools + run: | + curl -fsSL -o tla2tools.jar https://github.com/tlaplus/tlaplus/releases/download/v1.8.0/tla2tools.jar + echo "TLA_JAR=$PWD/tla2tools.jar" >> "$GITHUB_ENV" + + - name: Setup Lean + uses: leanprover/lean-action@v1 + with: + lake-package-directory: proofs + auto-config: false + build: true + use-github-cache: false + + - name: Verify + run: ./scripts-verify.sh + windows-typecheck: - name: Windows typecheck + name: Windows typecheck and tests runs-on: windows-latest steps: - name: Checkout @@ -90,3 +154,30 @@ jobs: - name: Typecheck tests run: bun run typecheck:tests + + - name: Test + run: bun test + + macos: + name: macOS typecheck and tests + runs-on: macos-latest + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Setup Bun + uses: oven-sh/setup-bun@v2 + with: + bun-version: "1.4.4" + + - name: Install dependencies + run: bun install --frozen-lockfile + + - name: Typecheck + run: bun run typecheck + + - name: Typecheck tests + run: bun run typecheck:tests + + - name: Test + run: bun test diff --git a/.gitignore b/.gitignore index 3408525..dc379ac 100644 --- a/.gitignore +++ b/.gitignore @@ -6,7 +6,6 @@ dist/ .env.local .idea/ .vscode/ -*.tsbuildinfo .bun/ .pytest_cache/ __pycache__/ @@ -15,6 +14,11 @@ __pycache__/ venv/ .tsbuildinfo +# Build and write artifacts that must never be committed +*.tgz +*.bak +*.tmp + # Contributor-only docs that are NOT shipped to npm and NOT versioned in git. # They are kept locally for development and live in AGENTS.md / TODO.md, # but the canonical, public roadmap and contributor guide live on GitHub: diff --git a/CHANGELOG.md b/CHANGELOG.md index 3fe76d5..f0cd52b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,155 @@ # Changelog +## 3.0.0 + +Byte-stable writes, a hardened tool boundary, and measured performance. The one +breaking change for existing callers is `ipynb_export`'s output extension; it is +first so it is easy to find. + +### Breaking + +- `ipynb_export` refuses an `outputPath` that does not end in `.md`, `.markdown`, + `.py`, `.txt` or `.rst` (after the win32 trailing dot/space normalization). + Previously any path that was not a `.ipynb` was written, which let a mistaken + prompt overwrite `.env`, `package.json` or a key file; the tool description + states the restriction. + +### Correctness + +- Writes are byte-stable (issue #2): the zod schemas validate only, and the raw + `JSON.parse` object is passed through unchanged (`applyNotebookDefaults` is + pure and returns a clone), so no write re-emits the notebook in + schema-declaration order. `src/utils/json-patch.ts` splices only the changed + values into the stored text, so untouched bytes keep their key order, layout, + escapes, and number literals. +- `ipynb_edit` mirrors the stored `source` shape: a notebook that stores line + arrays keeps line arrays (split like nbformat/`splitlines(keepends=True)`); a + single-string notebook keeps one string. Inserted cells inherit the shape of + the notebook's first cell. +- `ipynb_run save=true` splits the `stream.text`/text-mime strings that + `nbformat.read` rejoins when the notebook stores `source` as line arrays, so + saving outputs does not reflow those outputs. +- `ipynb_run save=true` gives every cell its own share of `maxOutputChars` + instead of draining one pool: later cells used to be persisted with empty + `stdout` over real output. Raw MIME bundles are persisted verbatim, so a + `text/html` or `image/png` display data survives a save instead of being + replaced by a `text/plain` summary. +- Defaulted keys (`metadata`, cell `outputs`) are inserted in sorted position + when the object's keys are already sorted, and appended otherwise, so an + existing key order is never reordered to make room for a default. +- A code cell that omits `execution_count` is accepted (nbformat treats the field + as optional) and a rewrite keeps the key absent instead of injecting it. +- Union validation failures name the offending field and the accepted values + (`cells.0.cell_type: expected "markdown"`) instead of collapsing to + `Invalid input`. +- Deeply nested values are refused with the depth limit named (512) instead of + surfacing a `Maximum call stack size exceeded`. +- A custom JSON Schema is generated with `additionalProperties: false` and the + `ipynb_read` / `ipynb_outputs` argument rules, so a misspelled argument or a + call the tool would reject is refused before it runs. A misspelled + `clear_outputs` used to be dropped and wiped outputs. +- `truncateMarkdown` no longer emits a lone surrogate when a budget splits an + astral character. +- A value JSON cannot represent (`undefined`, `BigInt`, a cycle) is refused with + an actionable message instead of being dropped and reported as a successful + write. + +### Data safety and atomicity + +- A notebook whose bytes are not valid UTF-8, or that starts with a BOM, is + rejected at read time instead of being decoded with replacement characters + and silently rewritten later. +- A tool call cancelled during the permission prompt writes nothing; a retried + insert or delete cannot apply twice. +- A write that another process replaces immediately after the rename fails with + a concurrent-replacement error instead of reporting success for a change that + is no longer in the file, and a file deleted right after the rename is + reported instead of silently succeeding. +- A write refused by a parent-directory swap no longer leaves the full new + notebook content behind as a hidden `.tmp`: cleanup tracks wherever the temp + moved and sweeps the unique name beside the original directory. +- The notebook write and the export are fsynced (content and directory, on + POSIX), so a returned success survives a crash. +- The parent directory is re-resolved and the containment re-checked immediately + before the rename, for notebook writes and for the LSP sidecar. +- An unreadable target is refused by the pre-rename revision re-read instead of + warning and writing anyway. +- Windows path confinement no longer accepts a drive root, a path on another + drive, or an outside path whose ancestor is a drive root; the regression was + found on a real Windows host and CI now runs the suite there. + +### Performance + +- `isMultiline` no longer scans to the end of the document per node, which made + compact notebooks quadratic: a 256k-key compact object fell from 6.8 s to + 0.76 s. +- `sanitizeTerminal` skips the whole examined window after an unterminated OSC + introducer: 40 MB of `ESC ]` noise fell from 4.1 s to 0.10 s. +- `formatOutputs` bounds a JSON dict before serializing it: 1000 sections of + 100k keys fell from 5.6 s to 7 ms and is now constant in the section count. +- The patcher builds its node tree from offsets and parses the value once + natively; array nodes store item spans and materialize only the changed ones. + A one-cell edit in a 17 MB / 64k-cell notebook fell from 1048 ms to roughly + 400-550 ms and the patch allocation from ~240 MB to ~43 MB. +- Non-ASCII `ensureAscii` escaping uses a lookup table instead of per-character + concatenation: a 10 MB string fell from 2094 ms / +1992 MB to 485 ms / +282 MB. +- `realpathWithRetry` stops retrying a genuinely absent path: a missing path + fell from 8.9 ms to 0.62 ms, and a new notebook several directories deep is + created in milliseconds. +- `scripts/bench-alloc.ts` pins the per-patch allocation with a fixed workload + (42-44 MB against a 60 MB ceiling and 161-171 MB for the previous tree); + `scripts/bench-writes.ts` asserts time and RSS budgets for a compact notebook, + a large per-cell output, non-ASCII escaping, an object-heavy patch and a + 17 MB edit. + +### Kernel and Python helper + +- A warm-kernel response must echo a per-request nonce: a notebook cell shares + the helper's stdout, so `os.write(1, '{"id":N,...}')` could settle another + request (and `save=true` persisted the forged output). Helpers that do not + advertise the nonce keep working. +- A kernel that dies under nbclient is torn down and the next request starts a + fresh kernel instead of failing until an explicit restart. +- An aborted or timed-out request no longer kills the shared kernel for other + in-flight requests. +- A queued `shutdown` preempts a running cell instead of waiting for it. +- The helper validates `timeoutMs` and `maxOutputChars` and returns a structured + error instead of a traceback and exit 1; a missing `pip` degrades the `env` + report to an empty package list instead of failing it; a serve request that + names a different notebook is refused instead of silently running the init + notebook. +- The helper exits when its parent disappears, so a plugin crash no longer + leaves an orphaned helper and kernel running until the cell ends. +- `MAX_HELPER_STDOUT_BYTES` is compared against UTF-8 bytes, and an aborted + oversized line clears its request timer instead of killing the next request. + +### Tooling, proofs and specs + +- The silence guard also matches `.catch(() => identifier)` forms; every + deliberately silent site is inventoried in `docs/contributing.md`. +- `scripts-vacuity.sh` ships the non-vacuity probes the guide promises: it + builds a temporary inverse invariant for all 17 checked states and fails when + TLC does not violate it. `scripts-verify.sh` runs it. +- Lean: sortedness is modelled over the UTF-16 unit order the shipped comparator + uses, `MarkdownSafe` records the clamped case and the well-formedness property, + and `NotebookDefaults` states key/value stability rather than only + "present implies noop". +- TLA+: `KernelWarningRing` gained a dishonest twin, and the scope each model + actually covers (win32 replace, `DeliveredBounded`) is stated in the module. +- `prepack` now verifies the packed file set (`server.js`, + `python/ipynb_runner.py`, docs) and greps `dist/index.js` for strings from the + current sources, so a stale or incomplete package cannot ship. +- CI: the test job retries up to three times, annotates every failing test and + uploads every attempt's log; Windows and macOS jobs run the suite. +- The LSP materialized sidecar is not rewritten when its content is unchanged, + preserving its mtime. The diagnostics temp file is still rewritten per call. + +### Documentation + +- `README`, `CHANGELOG` and `docs/` statements were checked against measured + behavior: the byte-stability claims, the defaulted-key insertion, the sidecar + no-rewrite scope, and the inode check's actual reach. + ## 2.0.0 - OpenCode V2-only plugin (`@opencode/plugin` 2.2.2). The V1 `server()` export is removed. diff --git a/README.md b/README.md index a93a90a..aa9a436 100644 --- a/README.md +++ b/README.md @@ -18,7 +18,7 @@ The plugin is **opt-in**, distributed via npm, and does not modify the OpenCode ## Installation -OpenCode 2.x loads plugins from the `plugins` key. Until the V2 line (`2.0.0`) is published, point OpenCode at a checkout directory: +OpenCode 2.x loads plugins from the `plugins` key. Point OpenCode at a checkout directory for an unreleased change: ```json { @@ -27,15 +27,17 @@ OpenCode 2.x loads plugins from the `plugins` key. Until the V2 line (`2.0.0`) i } ``` -The npm `latest` tag still points at the V1 `0.1.2` package, which does **not** load in OpenCode 2. After the V2 package is published, the versioned form is: +The V2 line is published from `3.0.0` onward, so the versioned form is: ```json { "$schema": "https://opencode.ai/config.json", - "plugins": ["opencode-ipynb@2.0.0"] + "plugins": ["opencode-ipynb@3.0.0"] } ``` +Anything below `2.0.0` is the V1 package, which does **not** load in OpenCode 2. + `opencode.example.jsonc` is a machine-independent local example. Or run directly from this repo: @@ -55,7 +57,7 @@ Then add the **absolute path** to this checkout to the `plugins` array in your ` | -------------------- | ------- | | `ipynb_inspect` | Compact summary: kernel/language metadata, cell table, output stats, execution-order warnings, optional missing-package checks. | | `ipynb_read` | Granular read of one cell or a range, with optional outputs/errors/metadata/images and truncation limits. | -| `ipynb_edit` | Safe per-cell source edit with a concise confirmation, output clearing policy, permission gate, and per-file lock. | +| `ipynb_edit` | Safe per-cell source edit with a concise confirmation, output clearing policy, permission gate, and in-process per-file lock. | | `ipynb_cell_insert` | Insert a code/markdown/raw cell at a target index, or append when the index is omitted. | | `ipynb_cell_delete` | Delete one cell by index and return a preview of the deleted source. | | `ipynb_cell_move` | Move one cell to a new index. | @@ -124,6 +126,10 @@ ipynb_export({ `ipynb_edit` returns a concise confirmation (cell, file, type, and whether outputs were cleared) instead of echoing the old/new source or a diff. The model already has the source it sent, so the extra text only spends tokens. +**Byte-stable writes.** A write splices only the changed values into the stored JSON, so untouched bytes survive: key order, `source` shape (a line array stays a line array, a string stays a string), indentation (including widths wider than `JSON.stringify`'s 10-space cap), inline vs expanded arrays, line endings (LF/CRLF), `\uXXXX` escapes, number literals, and the trailing newline. If a splice cannot be trusted, the writer falls back to re-serializing the whole notebook, which preserves key order and the file's line endings but normalizes whitespace. A file that `nbformat` itself would reject — a UTF-8 BOM prefix or bytes that are not valid UTF-8 — fails at read time with a parse error (matching `nbformat`'s `NotJSONError`/`UnicodeDecodeError`) and is never silently rewritten. `ipynb_run save=true` also re-splits the `stream.text`/text-mime strings that `nbformat.read` rejoins (when the notebook stores `source` as line arrays), so saving outputs does not reflow those outputs. `ipynb_clean` is the exception by design: `normalizeSource` (default `true`) intentionally rewrites `source` arrays to strings, so pass `normalizeSource: false` when you want a minimal diff. + +Note that `clearOutputs: "auto"` (the `ipynb_edit` default) sets `execution_count` to `null` on a code cell whose source changed, even when the notebook committed a specific count. Use `clearOutputs: "never"` when editing a notebook exported from a workspace that stores execution counts and you want to preserve them. + After code-changing tools, the plugin runs pyright on the notebook's virtual Python document for **Python notebooks only** and appends errors in the same block shape used by [`opencode-v2-lsp-support`](https://github.com/christensenjairus/opencode-v2-lsp-support): ```text @@ -153,7 +159,7 @@ The cell-mapped errors are also available as `metadata.notebookDiagnostics`; `me Note that a tool-level `edit: deny` also removes tools that declare `options.permission: "edit"` from the model catalog; mixed tools remain visible and fail when their write branch asserts `edit`. - Tools that always mutate (`ipynb_edit`, `ipynb_cell_insert`, `ipynb_cell_delete`, `ipynb_cell_move`, `ipynb_clean`) declare `options.permission: "edit"`, and `ipynb_run` declares `"shell"`. `ipynb_lsp` declares `"lsp"`; diagnostics asks for `lsp`/`read` on the notebook and `edit` on its temporary analysis file; materialize asks for `read`/`lsp` on the notebook and `edit` on the sidecar path. Read-only tools (`ipynb_inspect`, `ipynb_read`, `ipynb_repro`) declare `"read"` and also assert `read` on the notebook path. When they need Python, they assert `shell` before spawning it: `ipynb_repro` always does, and `ipynb_inspect` only when `checkMissingPackages=true`. This ordering means a denied `shell` action prevents the subprocess entirely. `ipynb_doctor` also asserts `shell` for the interpreter before probing it. Mixed read/write tools (`ipynb_outputs`, `ipynb_export`) do not declare a tool-level permission; their read branches assert `read` and their writes assert `edit`. `ipynb_doctor` declares no permission action. `ipynb_kernel` declares no tool-level action, but `restart`/`shutdown` assert `shell` on the kernel's notebook path before stopping it. -- `PathService` rejects paths that resolve outside of the OpenCode worktree, and `NotebookFileService` pins the resolved real path inside the worktree before reading or writing. Symlink aliases share a lock and writes update the real target rather than replacing the link. The lock manager keys by real path and serializes per-file writes to prevent accidental corruption. +- `PathService` rejects paths that resolve outside of the OpenCode worktree, and `NotebookFileService` pins the resolved real path inside the worktree before reading or writing. Symlink aliases share a lock and writes update the real target rather than replacing the link. The lock manager keys by real path and serializes per-file writes within one process to prevent accidental corruption. Independent processes do not share the lock: if two of them write the same notebook, the later rename wins, and the writer whose change was replaced now fails with a concurrent-replacement error instead of reporting success. Both a replacing rename and an in-place rewrite (what `nbformat.write` and most editors do) are detected: the write compares the target inode and re-reads the target's text after the rename. - The Python execution helper is an opt-in, isolated subprocess; it does not auto-install Jupyter. The user installs `python/requirements.txt` only when they want real execution. ## Context control @@ -365,7 +371,7 @@ bun run build npm pack --dry-run ``` -The `2.0.0` release is the V2-only line. The npm `latest` tag currently points at the V1 `0.1.2` package; publish `2.0.0` before advertising the package name as a V2 install. If you publish under a scope instead, update `package.json`, the install snippet, and this release tag convention together. +The `3.0.0` release is the current V2-only line (`2.0.0` was the first). The npm `latest` tag must point at a `2.0.0`-or-newer package for the bare package name to load in OpenCode 2. If you publish under a scope instead, update `package.json`, the install snippet, and this release tag convention together. ## Effect LSP setup (for development) diff --git a/dbg-kill.ts b/dbg-kill.ts new file mode 100644 index 0000000..e69de29 diff --git a/docs/architecture.md b/docs/architecture.md index 85fba8f..e1cdf6a 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -54,6 +54,13 @@ per-call instances but shares module-level state where required: - `NotebookFileService`: validates notebooks, serializes writes by **real path** (so symlink aliases share a lock), and pins the real path inside the worktree before reading/writing. Temp files are written with `wx` and renamed. + The zod schemas are **validation-only**: reads return the raw `JSON.parse` + object, and `src/utils/json-patch.ts` splices only the changed values into the + stored text, so untouched bytes keep their layout (indentation, inline arrays, + escapes, number literals, line endings). Do not write `parsed.data`; + `z.object` rebuilds its output in declaration order and reflows the notebook + (issue #2). Keep `test/unit/notebook-write-order.test.ts` and + `test/unit/notebook-layout.test.ts` green. - `NotebookEditService`, `NotebookExecutionService`, `NotebookReadService`, etc.: feature logic. `NotebookEditService.editCell` returns the in-memory notebook plus cell metadata and a `changed` flag internally; the tool layer @@ -61,11 +68,32 @@ per-call instances but shares module-level state where required: - `PythonService` instances are shared by option identity; kernel managers are scoped per plugin instance/context. +Every write returns a `WriteOutcome` from `writeAtomic` (`mode`, plus a `reason` +when the JSON splice could not be trusted). All writers surface it as +`writeMode`/`writeModeReason` metadata, and a fallback rewrite also records a +`json-patch` warning, so a degradation that reformats the file is never silent. +Cross-cutting failures flow through `src/utils/warnings.ts` (`WarningSink`) into +tool output text and `metadata.warnings`; kill-path and shell-refusal failures +are recorded the same way (`cleanup`, `shell-command`), and `ipynb_doctor` +reports an invalid `OPENCODE_IPYNB_OPTIONS` through the services' +`envOptionsError`. Each deliberately silent site is inventoried in +`docs/contributing.md` and enforced by `test/unit/silence-allowlist.test.ts`. + Path checks happen before work, and the file service resolves and verifies the real path at use time (reads use the resolved path; writes target the resolved file/parent). This removes the practical symlink-swap window for notebook I/O -without requiring a directory-fd API from Node. Residual path-based races are -documented as a limitation rather than claimed impossible. Bare `python` and +without requiring a directory-fd API from Node. A parent-directory swap between +the check and the rename remains possible for a local actor that can rename +directories inside the worktree; that residual race is documented as a +limitation rather than claimed impossible. The write region is uninterruptible, +so the file lock is released only after the rename settles, and after the +rename the write compares the target inode with the temp file's and, when the +inode is unchanged, re-reads the target: a writer that replaced or rewrote the +notebook at that path is reported as a concurrent-replacement error instead of +a lost write reported as success. Those checks are path based, so they catch a +competitor that writes at the same path; if the parent directory is moved after +the final containment recheck and the temp is carried across the boundary, the +call still succeeds, which is the documented parent-swap limitation above. Bare `python` and `pyright` names are resolved to absolute PATH entries before spawning; if pyright is not found, the plugin fails closed instead of letting `cmd.exe` search the project cwd. Relative `pythonPath`/`pyrightPath` values are rejected. @@ -125,6 +153,12 @@ state. `Data.TaggedError`, etc.). Services are plain constructors returned to the tool layer; they are not registered in a `Context`/`Layer` because every tool call builds a context-scoped instance. +- Explanatory comments are not used in `src/`; behaviour is pinned by tests, + public types, and `docs/`. The intent behind a non-obvious branch belongs in a + test name. +- Formal verification lives outside the build: `specs/` models the write lock + and proves the lost-update hazard, `proofs/` proves the source splitting + round-trip. `scripts-verify.sh` runs both; CI executes it in a separate job. - Custom tool names cannot use OpenCode's native edit renderer; the plugin keeps edit results concise instead of shipping a renderer patch. - Materialization is file-based, not LSP 3.17 notebook synchronization. diff --git a/docs/contributing.md b/docs/contributing.md index 158b3b1..1b8c537 100644 --- a/docs/contributing.md +++ b/docs/contributing.md @@ -111,6 +111,11 @@ read `process.env` for options inside tools/services. kernel tests. - Prefer a failing regression test before a fix. Security tests must cover both the normal path and the symlink/escape path. +- Notebook writes must stay byte-stable: keep `test/unit/notebook-write-order.test.ts` + and `test/unit/notebook-layout.test.ts` green. Services work with the raw + `JSON.parse` object, never `Schema.parse` output (which reorders keys), keep + it unmutated (`applyNotebookDefaults` is pure and returns a clone), and pass + the `format` and `previousText` from `readWithText` to `writeAtomic`. - When changing the hook, test the changed/no-op matrix (`changed: false`, output-only clears, failed tools, `save: false`). @@ -148,3 +153,141 @@ Effect 4 conventions used here: `Cause.findErrorOption`/`Cause.squash` so host permission errors propagate. - Prefer `Data.TaggedError` for domain errors and keep `_tag` checks out of business logic. + +## Review protocol + +Every review, human or agent, must produce evidence rather than confidence. + +1. **Consult the installed dependency source first.** `node_modules/effect`, + `node_modules/zod`, `node_modules/@types/bun`, `node_modules/@opencode/plugin` + and `node_modules/@opencode/schema`, plus `.venv/lib/*/site-packages/nbformat` + for notebook semantics. Never judge an API from memory. +2. **Use the language server.** `documentSymbol` to map a changed module, + `goToDefinition` and `hover` for anything not local, and `findReferences` + before changing a function, type, or shared contract. Report which symbols + and references were inspected; claim no navigation that did not happen. +3. **Model the state machines.** `specs/` holds TLA+ models; `tlc` must agree. + Concurrency, locking, and revision checks belong there, not in prose. + Each good spec is paired with a dishonest twin that must violate its + declared `.expect` line, and every checked invariant is probed for + vacuity by `scripts-vacuity.sh` (run from `scripts-verify.sh`): it builds a + temporary inverse invariant per checked state and requires TLC to violate + it, proving the pinned path is reachable. Two assumptions are stated in the modules + themselves: the save spec collapses the under-lock recheck and the + rename into one step (the in-process file lock serializes plugin + writers; a non-cooperating external writer keeps a residual window no + in-process protocol can close), and the lock spec keeps + `ExternalWrite` enabled while a writer holds the lock, because + external writers never take our semaphore. +4. **Prove the pure properties.** `proofs/` holds the Lean 4 development; + `lake build` must succeed. Shape and round-trip invariants belong there. +5. **Test both ways.** Run the suite, and run the opposite mutation: if a fix + cannot be reverted to make a test fail, the test proves nothing. +6. **Never accept silence.** A swallowed failure is a defect. Record it through + `src/utils/warnings.ts` or surface it in the tool result; if a best-effort + step is genuinely expected to fail, say why in the report rather than + discarding it. +7. **No explanatory comments in `src/`.** Intent belongs in the public types, + the tests, and these docs. +8. **Report the config.** State the Bun/Node/Python versions and the exact + commands used, so the result can be reproduced. + +`./scripts-verify.sh` runs the Lean build and every TLA+ model. `bun run +scripts/bench-writes.ts` asserts that write cost stays linear in the notebook +size; a superlinear result fails the build. CI runs both. + +### Host smoke test + +The suite runs against an in-process harness. Before a release, load the built +plugin in a real OpenCode run and confirm the tool surface end to end: + +```bash +bun run build +mkdir -p /tmp/opencode/e2e && cd /tmp/opencode/e2e +printf '{"plugins":[{"package":"/abs/path/to/opencode-ipynb","options":{"pythonPath":"/abs/path/to/.venv/bin/python"}}]}\n' > opencode.jsonc +# create a two-cell n.ipynb here, then: +opencode run --standalone --archived --format json --auto \ + "Call ipynb_inspect once on n.ipynb and reply with the cell count." +opencode run --standalone --archived --format json --auto \ + "Call ipynb_edit once on n.ipynb to set cell 0 source to 'x = 2' with clearOutputs 'never'." +``` + +Expect the inspect output to report the right number of cells, the edit +metadata to say `writeMode: "patched"`, and the notebook diff to touch exactly +the edited line. Anything else means the host path diverges from the harness. + +### Deliberately silent sites + +These failures stay unreported on purpose; every other swallowed failure +must reach a `WarningSink`. `test/unit/silence-allowlist.test.ts` scans the +whole source — including multi-line catch blocks, which a line-based scan +cannot see — and fails unless each silent site appears with its exact count: + +- Chaining an existing lock (`await previous.catch(() => {})` in + `KernelManager` and `notebook-diagnostics`) — the previous holder already + ran; there is no intent to defeat. +- The host's `context.progress()` (`plugin-v2`) — a refused progress update + is not a plugin failure. +- Existence and executability probes (`PythonService` ×3, the PATH scan in + `notebook-diagnostics`, the PATH scan in `plugin-options`) — a candidate + that is missing or not executable is the normal negative result of a + probe, not a failure worth reporting. +- Realpath fallbacks (`diagnosticHash` in `notebook-diagnostics`, + `virtual-materialize`, the revision pin in `revision.ts`, the kernel key in + `tools/kernel.ts`, and the worktree/file probes in `NotebookFileService`) — + when realpath fails, the caller falls back to the lexical path, which is its + documented behavior. The scan matches `.catch(() => )` as well as + empty bodies, so this form must be listed too. + +Also deliberate, though not empty-catch sites the scan can count: + +- `loadNotebookDocument` dropping a failed `resolvePythonPath` — the hook + path has no user to tell and interpreter auto-discovery continues; the + tool paths surface a bad `pythonPath` loudly through `pythonPathError`. + +Everything else must reach a `WarningSink`, and the cases below announce +themselves explicitly rather than staying silent: + +- A failed patch falling back to a full rewrite records a `json-patch` + warning and the tool reports `writeMode`/`writeModeReason` metadata. +- Kill-path failures are recorded through the `cleanup` warning source; a + kill of an already-dead process (ESRCH) is success, not a failure. +- An invalid `OPENCODE_IPYNB_OPTIONS` is surfaced through the services' + `envOptionsError` and a warning section in `ipynb_doctor`. + +### Known limitations + +- **Kernel caches are per scope, not LRU-bounded.** One kernel manager (and one + live kernel) exists per session directory and notebook path, and both are + released when the plugin's dispose runs (`disposeSharedKernelManager`, + `disposeAll`). A long-lived host that creates many sessions without ever + unloading the plugin accumulates them; a measured 200-notebook probe showed + no fd, child-process or listener growth, so this is a policy gap rather than + a leak. Bounding it would need an idle-kernel reaper, which changes when a + warm kernel disappears and is deliberately not done here. +- **Unreproduced suite failure.** One full-suite run on this branch reported a + single failure that was never named. Fifteen further runs (six inside a 2 GB + cgroup, nine as three concurrent instances, plus ten earlier ones) were + clean, so the cause is not memory pressure or parallelism. CI now retries the + suite up to three times, prints and annotates every failing test name, and + uploads every attempt's log, so the next occurrence is captured instead of + lost. Locally, capture with `bun test 2>&1 | tee run.log`. +- **Write-path memory.** A one-cell edit in a 17 MB / 64k-cell notebook + measured 91-231 MB RSS and 421-585 ms over eighteen runs on this machine. + Array nodes store item spans and only materialize the child nodes for the + span that actually differs, which halved the patch allocation from ~240 MB + to ~120 MB; the pre-span implementation measured 213-288 MB and 464-663 ms. + Those end-to-end ranges overlap, so the write bench enforces only absolute + budgets (400 MB, 900 ms) there. The implementation difference is pinned + separately by `scripts/bench-alloc.ts`, which spawns a fresh process, patches + a fixed 64k-cell notebook, and measures `heapUsed` immediately around + `patchJsonTextDetailed`: the span implementation allocates 42.5-43.6 MB per + patch while the eager node tree allocated 161-171 MB, and the guard fails + above a 60 MB heap median and 40 MB of cumulative RSS growth. Two signals are + needed because Bun only moves `heapUsed` at collection boundaries: a run that + retains every output measures 0 MB there but grows RSS by ~85 MB across five + runs, which the growth bound catches. On win32 Bun freezes `heapUsed` (a + retained 20M-element array reports 0 MB), so the guard prints SKIP there + rather than a false green; the Linux CI job is where it discriminates. An object-heavy notebook (one key changed in 64k-key metadata) + costs ~2-9 MB and is guarded on time only. Retained memory after a forced GC + is ~25 MB, so the remainder is transient garbage. diff --git a/package.json b/package.json index a4d80cc..8ad2995 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "opencode-ipynb", - "version": "2.0.0", + "version": "3.0.0", "description": "OpenCode community plugin that adds robust .ipynb (Jupyter Notebook) support: inspect, read, edit, run, outputs, clean, export, reproducibility reports, and warm kernels.", "type": "module", "packageManager": "bun@1.4.4", @@ -52,7 +52,7 @@ "test": "bun test", "lint:effect": "tsc --noEmit", "prepare:effect-lsp": "effect-language-service patch", - "prepack": "node -e \"for (const f of ['dist/index.js','dist/index.d.ts','dist/lsp.js','dist/lsp.d.ts','dist/rpc.js','dist/rpc.d.ts']) if (!require('node:fs').existsSync(f)) { console.error(f + ' is missing; run: bun run build'); process.exit(1) }\"", + "prepack": "bun run scripts/prepack-check.ts", "test:coverage": "bun test --coverage" }, "keywords": [ diff --git a/proofs/.gitignore b/proofs/.gitignore new file mode 100644 index 0000000..01f8cdb --- /dev/null +++ b/proofs/.gitignore @@ -0,0 +1 @@ +.lake/ diff --git a/proofs/OpencodeIpynb.lean b/proofs/OpencodeIpynb.lean new file mode 100644 index 0000000..b4b9263 --- /dev/null +++ b/proofs/OpencodeIpynb.lean @@ -0,0 +1,6 @@ +import OpencodeIpynb.ApplyEdits +import OpencodeIpynb.FormatSource +import OpencodeIpynb.InsertSorted +import OpencodeIpynb.MarkdownSafe +import OpencodeIpynb.NotebookDefaults +import OpencodeIpynb.SourceLines diff --git a/proofs/OpencodeIpynb/ApplyEdits.lean b/proofs/OpencodeIpynb/ApplyEdits.lean new file mode 100644 index 0000000..eaa7bb5 --- /dev/null +++ b/proofs/OpencodeIpynb/ApplyEdits.lean @@ -0,0 +1,86 @@ +namespace OpencodeIpynb + +structure Edit where + start : Nat + stop : Nat + text : List Char + +def applyEditsFrom (text : List Char) (cursor : Nat) : List Edit → Option (List Char) + | [] => some (text.drop cursor) + | edit :: rest => + if edit.start < cursor then none + else + match applyEditsFrom text edit.stop rest with + | none => none + | some tail => + some ((text.drop cursor).take (edit.start - cursor) ++ edit.text ++ tail) + +def applyEdits (text : List Char) (edits : List Edit) : Option (List Char) := + applyEditsFrom text 0 edits + +def chainedFrom (cursor : Nat) : List Edit → Bool + | [] => true + | edit :: rest => decide (cursor ≤ edit.start) && chainedFrom edit.stop rest + +theorem chainedFrom_cons (cursor : Nat) (edit : Edit) (rest : List Edit) + (h : chainedFrom cursor (edit :: rest) = true) : + cursor ≤ edit.start ∧ chainedFrom edit.stop rest = true := by + simp [chainedFrom] at h + exact h + +theorem applyEdits_nil (text : List Char) : applyEdits text [] = some text := by + simp [applyEdits, applyEditsFrom] + +theorem applyEdits_single (text : List Char) (edit : Edit) : + applyEdits text [edit] = + some (text.take edit.start ++ edit.text ++ text.drop edit.stop) := by + simp only [applyEdits, applyEditsFrom] + rw [ite_eq_right (by omega : ¬ (edit.start < 0))] + simp + +theorem applyEdits_overlap_rejected (text : List Char) (e1 e2 : Edit) + (_hsorted : e1.start < e2.start ∨ (e1.start = e2.start ∧ e1.stop ≤ e2.stop)) + (hoverlap : e2.start < e1.stop) : + applyEdits text [e1, e2] = none := by + simp only [applyEdits, applyEditsFrom] + rw [ite_eq_right (by omega : ¬ (e1.start < 0))] + rw [ite_eq_left hoverlap] + +theorem applyEdits_two (text : List Char) (e1 e2 : Edit) + (_hvalid1 : e1.start ≤ e1.stop) (_hvalid2 : e2.start ≤ e2.stop) + (h : e1.stop ≤ e2.start) : + applyEdits text [e1, e2] = + some (text.take e1.start ++ e1.text ++ + ((text.drop e1.stop).take (e2.start - e1.stop) ++ e2.text ++ text.drop e2.stop)) := by + simp only [applyEdits, applyEditsFrom] + rw [ite_eq_right (by omega : ¬ (e1.start < 0))] + rw [ite_eq_right (by omega : ¬ (e2.start < e1.stop))] + simp + +def spliceAll (text : List Char) (cursor : Nat) : List Edit → List Char + | [] => text.drop cursor + | edit :: rest => + (text.drop cursor).take (edit.start - cursor) ++ edit.text ++ + spliceAll text edit.stop rest + +theorem applyEditsFrom_eq_spliceAll (text : List Char) (cursor : Nat) : + ∀ edits : List Edit, chainedFrom cursor edits = true → + applyEditsFrom text cursor edits = some (spliceAll text cursor edits) := by + intro edits + induction edits generalizing cursor with + | nil => intro _; simp [applyEditsFrom, spliceAll] + | cons edit rest ih => + intro h + obtain ⟨hle, hchain⟩ := chainedFrom_cons cursor edit rest h + simp only [applyEditsFrom] + rw [ite_eq_right (by omega : ¬ (edit.start < cursor))] + rw [ih edit.stop hchain] + simp [spliceAll] + +theorem applyEdits_chained_total (text : List Char) (edits : List Edit) + (_hvalid : ∀ e ∈ edits, e.start ≤ e.stop) + (h : chainedFrom 0 edits = true) : + applyEdits text edits = some (spliceAll text 0 edits) := + applyEditsFrom_eq_spliceAll text 0 edits h + +end OpencodeIpynb diff --git a/proofs/OpencodeIpynb/FormatSource.lean b/proofs/OpencodeIpynb/FormatSource.lean new file mode 100644 index 0000000..bd3a842 --- /dev/null +++ b/proofs/OpencodeIpynb/FormatSource.lean @@ -0,0 +1,37 @@ +import OpencodeIpynb.SourceLines + +namespace OpencodeIpynb + +inductive Shape where + | string + | array + deriving DecidableEq, Repr + +def renderSource : Shape → List SChar → List (List SChar) + | .string, next => [next] + | .array, next => splitLines next + +theorem renderSource_flatten (shape : Shape) (next : List SChar) : + (renderSource shape next).flatten = next := by + cases shape with + | string => simp [renderSource] + | array => simp [renderSource, splitLines_flatten] + +theorem renderSource_string_unsplit (next : List SChar) : + renderSource .string next = [next] := rfl + +def renderEach (shapeOf : List SChar → Shape) (texts : List (List SChar)) : + List (List (List SChar)) := + texts.map (fun text => renderSource (shapeOf text) text) + +theorem renderEach_join (shapeOf : List SChar → Shape) (texts : List (List SChar)) : + (renderEach shapeOf texts).flatten.flatten = texts.flatten := by + induction texts with + | nil => simp [renderEach] + | cons text rest ih => + have ih' : + ((List.map (fun t => renderSource (shapeOf t) t) rest).flatten).flatten = rest.flatten := ih + simp only [renderEach, List.map_cons, List.flatten_cons, List.flatten_append] + rw [renderSource_flatten, ih'] + +end OpencodeIpynb diff --git a/proofs/OpencodeIpynb/InsertSorted.lean b/proofs/OpencodeIpynb/InsertSorted.lean new file mode 100644 index 0000000..c7ce84d --- /dev/null +++ b/proofs/OpencodeIpynb/InsertSorted.lean @@ -0,0 +1,265 @@ +namespace OpencodeIpynb + +variable {α : Type} [BEq α] [LawfulBEq α] + +def hasKey : List α → α → Bool + | [], _ => false + | k :: rest, key => if k == key then true else hasKey rest key + +omit [LawfulBEq α] in +theorem hasKey_cons_true (k : α) (rest : List α) (key : α) + (hk : (k == key) = true) : hasKey (k :: rest) key = true := by + simp only [hasKey] + rw [ite_eq_left hk] + +omit [LawfulBEq α] in +theorem hasKey_cons_false (k : α) (rest : List α) (key : α) + (hk : ¬ (k == key) = true) : hasKey (k :: rest) key = hasKey rest key := by + simp only [hasKey] + rw [ite_eq_right hk] + +omit [LawfulBEq α] in +theorem hasKey_cons_tail_true (k : α) (rest : List α) (key : α) + (hk : ¬ (k == key) = true) (hmem : hasKey rest key = true) : + hasKey (k :: rest) key = true := by + rw [hasKey_cons_false k rest key hk, hmem] + +omit [LawfulBEq α] in +theorem hasKey_cons_inv (k : α) (rest : List α) (key : α) + (h : hasKey (k :: rest) key = true) (hk : ¬ (k == key) = true) : + hasKey rest key = true := by + rw [hasKey_cons_false k rest key hk] at h + exact h + +def isSortedBy (lt : α → α → Bool) : List α → Bool + | [] => true + | [_] => true + | a :: b :: rest => lt a b && isSortedBy lt (b :: rest) + +def insertSortedAux (lt : α → α → Bool) (key : α) : List α → List α + | [] => [key] + | k :: rest => + if lt key k then key :: k :: rest else k :: insertSortedAux lt key rest + +def insertSortedBy (lt : α → α → Bool) (present : List α → α → Bool) + (keys : List α) (key : α) : List α := + if present keys key then keys + else if isSortedBy lt keys then insertSortedAux lt key keys + else keys ++ [key] + +omit [BEq α] [LawfulBEq α] in +theorem insertSortedBy_noop (lt : α → α → Bool) (present : List α → α → Bool) + (keys : List α) (key : α) (hmem : present keys key = true) : + insertSortedBy lt present keys key = keys := by + simp only [insertSortedBy] + rw [ite_eq_left hmem] + +omit [BEq α] [LawfulBEq α] in +theorem insertSortedBy_append (lt : α → α → Bool) (present : List α → α → Bool) + (keys : List α) (key : α) + (hnc : ¬ present keys key = true) (hns : ¬ isSortedBy lt keys = true) : + insertSortedBy lt present keys key = keys ++ [key] := by + simp only [insertSortedBy] + rw [ite_eq_right hnc, ite_eq_right hns] + +omit [BEq α] [LawfulBEq α] in +theorem insertSortedAux_positions (lt : α → α → Bool) (key : α) : + ∀ keys : List α, + ∃ pre post : List α, + insertSortedAux lt key keys = pre ++ [key] ++ post ∧ keys = pre ++ post := by + intro keys + induction keys with + | nil => + refine ⟨[], [], ?_, ?_⟩ <;> rfl + | cons k rest ih => + obtain ⟨pre, post, hres, hrest⟩ := ih + by_cases h : lt key k = true + · refine ⟨[], k :: rest, ?_, ?_⟩ + · simp only [insertSortedAux] + rw [ite_eq_left h] + rfl + · rfl + · refine ⟨k :: pre, post, ?_, ?_⟩ + · simp only [insertSortedAux] + rw [ite_eq_right h, hres] + simp [List.cons_append] + · rw [hrest] + simp [List.cons_append] + +omit [BEq α] [LawfulBEq α] in +theorem insertSortedBy_positions (lt : α → α → Bool) (present : List α → α → Bool) + (keys : List α) (key : α) (hnc : ¬ present keys key = true) : + ∃ pre post : List α, + insertSortedBy lt present keys key = pre ++ [key] ++ post ∧ keys = pre ++ post := by + simp only [insertSortedBy] + by_cases hmem : present keys key = true + · exact absurd hmem hnc + · by_cases hsort : isSortedBy lt keys = true + · rw [ite_eq_right hmem, ite_eq_left hsort] + exact insertSortedAux_positions lt key keys + · refine ⟨keys, [], ?_, ?_⟩ + · rw [ite_eq_right hmem, ite_eq_right hsort] + simp + · exact (List.append_nil keys).symm + +omit [BEq α] [LawfulBEq α] in +theorem isSortedBy_cons_head (lt : α → α → Bool) (a b : α) (rest : List α) : + isSortedBy lt (a :: b :: rest) = true → lt a b = true := by + intro h + simp [isSortedBy] at h + exact h.1 + +omit [BEq α] [LawfulBEq α] in +theorem isSortedBy_cons_tail (lt : α → α → Bool) (a b : α) (rest : List α) : + isSortedBy lt (a :: b :: rest) = true → isSortedBy lt (b :: rest) = true := by + intro h + simp [isSortedBy] at h + exact h.2 + +theorem insertSortedAux_sorted (lt : α → α → Bool) + (hconn : ∀ a b : α, ¬ lt a b = true → a = b ∨ lt b a = true) + (key : α) : + ∀ keys : List α, + isSortedBy lt keys = true → + ¬ hasKey keys key = true → + isSortedBy lt (insertSortedAux lt key keys) = true := by + intro keys + induction keys with + | nil => intro _ _; rfl + | cons k rest ih => + intro hsorted hnc + have hrestnc : ¬ hasKey rest key = true := by + intro hmem + cases hk : k == key with + | true => exact absurd (hasKey_cons_true k rest key hk) hnc + | false => exact absurd (hasKey_cons_tail_true k rest key (by simp [hk]) hmem) hnc + by_cases h : lt key k = true + · simp only [insertSortedAux] + rw [ite_eq_left h] + simp only [isSortedBy, Bool.and_eq_true] + exact ⟨h, hsorted⟩ + · have hne : key ≠ k := by + intro heq + rw [heq] at hnc + exact absurd (hasKey_cons_true k rest k (beq_self_eq_true k)) hnc + have hklt : lt k key = true := by + rcases hconn key k h with heq | hk + · exact absurd heq hne + · exact hk + have hrestsorted : isSortedBy lt rest = true := by + cases rest with + | nil => simp [isSortedBy] + | cons m ms => exact isSortedBy_cons_tail lt k m ms hsorted + have htail := ih hrestsorted hrestnc + cases rest with + | nil => + simp only [insertSortedAux] + rw [ite_eq_right h] + simp only [isSortedBy, Bool.and_eq_true] + refine ⟨hklt, ?_⟩ + simp + | cons m ms => + by_cases hm : lt key m = true + · simp only [insertSortedAux] + rw [ite_eq_right h, ite_eq_left hm] + simp only [isSortedBy, Bool.and_eq_true] + exact ⟨hklt, hm, hrestsorted⟩ + · have hkm : lt k m = true := isSortedBy_cons_head lt k m ms hsorted + have haux : insertSortedAux lt key (m :: ms) = m :: insertSortedAux lt key ms := by + simp only [insertSortedAux] + rw [ite_eq_right hm] + have htail := ih hrestsorted hrestnc + rw [haux] at htail + simp only [insertSortedAux] + rw [ite_eq_right h, ite_eq_right hm] + simp only [isSortedBy, Bool.and_eq_true] + exact ⟨hkm, htail⟩ + +theorem insertSortedBy_sorted (lt : α → α → Bool) (present : List α → α → Bool) + (hsound : ∀ keys : List α, ∀ key : α, hasKey keys key = true → present keys key = true) + (hconn : ∀ a b : α, ¬ lt a b = true → a = b ∨ lt b a = true) + (keys : List α) (key : α) + (hnc : ¬ present keys key = true) (hs : isSortedBy lt keys = true) : + isSortedBy lt (insertSortedBy lt present keys key) = true := by + have hnc' : ¬ hasKey keys key = true := fun hmem => hnc (hsound keys key hmem) + simp only [insertSortedBy] + rw [ite_eq_right hnc, ite_eq_left hs] + exact insertSortedAux_sorted lt hconn key keys hs hnc' + +def natLt (a b : Nat) : Bool := decide (a < b) + +theorem natLt_conn (a b : Nat) : ¬ natLt a b = true → a = b ∨ natLt b a = true := by + intro h + simp only [natLt, decide_eq_true_eq] at h + rcases Nat.lt_or_ge b a with hlt | hge + · exact Or.inr (by simp [natLt, hlt]) + · exact Or.inl (Nat.le_antisymm hge (Nat.not_lt.mp h)) + +theorem insertSortedBy_nat_sorted (keys : List Nat) (key : Nat) + (hnc : ¬ hasKey keys key = true) (hs : isSortedBy natLt keys = true) : + isSortedBy natLt (insertSortedBy natLt hasKey keys key) = true := + insertSortedBy_sorted natLt hasKey (fun _ _ hmem => hmem) natLt_conn keys key hnc hs + +def strLt (a b : String) : Bool := decide (a < b) + +theorem strLt_conn (a b : String) (h : ¬ strLt a b = true) : + a = b ∨ strLt b a = true := by + rcases Std.lt_trichotomy a b with hlt | heq | hgt + · exact absurd (by simp [strLt, hlt]) h + · exact Or.inl heq + · exact Or.inr (by simp [strLt, hgt]) + +def unitLtFrom : List Nat → List Nat → Bool + | [], [] => false + | [], _ :: _ => true + | _ :: _, [] => false + | x :: xs, y :: ys => + if x < y then true else if y < x then false else unitLtFrom xs ys + +theorem unitLtFrom_conn (a b : List Nat) (h : ¬ unitLtFrom a b = true) : + a = b ∨ unitLtFrom b a = true := by + induction a generalizing b with + | nil => + cases b with + | nil => exact Or.inl rfl + | cons y ys => + have hfalse : unitLtFrom [] (y :: ys) = true := rfl + exact absurd hfalse h + | cons x xs ih => + cases b with + | nil => exact Or.inr (by simp [unitLtFrom]) + | cons y ys => + by_cases hxy : x < y + · exact absurd (by simp [unitLtFrom, hxy]) h + · by_cases hyx : y < x + · exact Or.inr (by simp [unitLtFrom, hyx]) + · have htail : ¬ unitLtFrom xs ys = true := by + simpa [unitLtFrom, hxy, hyx] using h + rcases ih ys htail with heq | hlt + · left + have heqxy : x = y := by omega + rw [heqxy, heq] + · exact Or.inr (by simp [unitLtFrom, hxy, hyx, hlt]) + +theorem unitLtFrom_irrefl (a : List Nat) : unitLtFrom a a = false := by + induction a with + | nil => rfl + | cons x xs ih => simp [unitLtFrom, Nat.lt_irrefl, ih] + +theorem insertSortedBy_units_sorted (keys : List (List Nat)) (key : List Nat) + (hnc : ¬ hasKey keys key = true) (hs : isSortedBy unitLtFrom keys = true) : + isSortedBy unitLtFrom (insertSortedBy unitLtFrom hasKey keys key) = true := + insertSortedBy_sorted unitLtFrom hasKey (fun _ _ hmem => hmem) unitLtFrom_conn + keys key hnc hs + +/- The shipped `insertSorted` compares UTF-16 code units, which is lexicographic + order on the unit sequence (an astral character becomes a surrogate pair). + `utf16Units` maps a string to that sequence and `insertSortedBy_units_sorted` + proves sortedness for exactly that order. Lean's own `String` `<` is UTF-8 + byte order, so it is deliberately not used as the production order here. -/ +def utf16Units (s : String) : List Nat := + (s.toList.map fun c => + if c.toNat < 0x10000 then [c.toNat] + else + let n := c.toNat - 0x10000 + [0xD800 + n / 0x400, 0xDC00 + n % 0x400]).flatten diff --git a/proofs/OpencodeIpynb/MarkdownSafe.lean b/proofs/OpencodeIpynb/MarkdownSafe.lean new file mode 100644 index 0000000..74265ee --- /dev/null +++ b/proofs/OpencodeIpynb/MarkdownSafe.lean @@ -0,0 +1,141 @@ +namespace OpencodeIpynb + +def MAX_FENCE : Nat := 32 + +def clampChars (chars : List Char) (limit : Nat) : List Char := + if chars.length ≤ limit then chars else chars.take limit + +def closingOf : Option (Char × Nat) → List Char + | none => [] + | some (fenceChar, run) => ['\n'] ++ List.replicate run fenceChar ++ ['\n'] + +def truncateMarkdownWith (normalize squash stripTrailing : List Char → List Char) + (scanFence : List Char → Option (Char × Nat)) + (text : List Char) (maxChars : Nat) (hint : List Char) : List Char := + if (normalize text).length ≤ maxChars then normalize text + else + let budget := max 0 (maxChars - hint.length - 2 * MAX_FENCE) + let cut := squash ((normalize text).take budget) + clampChars (stripTrailing cut ++ closingOf (scanFence cut) ++ hint) maxChars + +theorem clampChars_le (chars : List Char) (limit : Nat) : + (clampChars chars limit).length ≤ limit := by + simp only [clampChars] + by_cases h : chars.length ≤ limit + · rw [ite_eq_left h] + exact h + · rw [ite_eq_right h] + exact List.length_take_le limit chars + +theorem truncateMarkdownWith_length_le (normalize squash stripTrailing : List Char → List Char) + (scanFence : List Char → Option (Char × Nat)) + (text : List Char) (maxChars : Nat) (hint : List Char) : + (truncateMarkdownWith normalize squash stripTrailing scanFence text maxChars hint).length ≤ + maxChars := by + simp only [truncateMarkdownWith] + by_cases h : (normalize text).length ≤ maxChars + · rw [ite_eq_left h] + exact h + · rw [ite_eq_right h] + exact clampChars_le _ maxChars + +theorem truncateMarkdownWith_identity (normalize squash stripTrailing : List Char → List Char) + (scanFence : List Char → Option (Char × Nat)) + (text : List Char) (maxChars : Nat) (hint : List Char) + (h : (normalize text).length ≤ maxChars) : + truncateMarkdownWith normalize squash stripTrailing scanFence text maxChars hint = + normalize text := by + simp only [truncateMarkdownWith] + rw [ite_eq_left h] + +theorem clampChars_within (chars : List Char) (limit : Nat) + (h : chars.length ≤ limit) : clampChars chars limit = chars := by + simp only [clampChars] + rw [ite_eq_left h] + +theorem saneBudget (maxChars hintLength : Nat) + (h : hintLength + 2 * MAX_FENCE ≤ maxChars) : + max 0 (maxChars - hintLength - 2 * MAX_FENCE) = + maxChars - hintLength - 2 * MAX_FENCE := by + omega + +theorem truncateMarkdownWith_hint_survives + (normalize squash stripTrailing : List Char → List Char) + (scanFence : List Char → Option (Char × Nat)) + (hsquash : ∀ chars, (squash chars).length ≤ chars.length) + (hstrip : ∀ chars, (stripTrailing chars).length ≤ chars.length) + (hfence : ∀ chars fence, scanFence chars = some fence → fence.2 ≤ MAX_FENCE) + (text : List Char) (hint : List Char) (maxChars : Nat) + (hbig : maxChars < (normalize text).length) + (hbudget : hint.length + 2 * MAX_FENCE ≤ maxChars) : + ∃ pre, + truncateMarkdownWith normalize squash stripTrailing scanFence text maxChars hint = + pre ++ hint := by + simp only [truncateMarkdownWith] + rw [ite_eq_right (by omega : ¬ ((normalize text).length ≤ maxChars))] + rw [saneBudget maxChars hint.length hbudget] + have hcut : (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE))).length ≤ + maxChars - hint.length - 2 * MAX_FENCE := + Nat.le_trans (hsquash _) (List.length_take_le _ _) + have hstripped : + (stripTrailing (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE)))).length ≤ + maxChars - hint.length - 2 * MAX_FENCE := + Nat.le_trans (hstrip _) hcut + have hclosing : + (closingOf (scanFence (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE))))).length ≤ + 2 + MAX_FENCE := by + cases hscan : + scanFence (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE))) with + | none => + simp [closingOf] + | some fence => + obtain ⟨fenceChar, run⟩ := fence + have hrun := hfence _ (fenceChar, run) hscan + simp only [closingOf] + simp + omega + refine ⟨ + stripTrailing (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE))) ++ + closingOf (scanFence (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE)))), + ?_⟩ + have htotal : + (stripTrailing (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE))) ++ + closingOf (scanFence (squash ((normalize text).take (maxChars - hint.length - 2 * MAX_FENCE)))) ++ + hint).length ≤ + maxChars := by + have hfenceVal : MAX_FENCE = 32 := rfl + rw [List.length_append, List.length_append] + omega + rw [clampChars_within _ maxChars htotal] + +/- When the caller's budget cannot hold the hint plus a fence pair the + truncator clamps the whole result, so the hint may be cut. The measured + boundary in the TS is `maxChars < hint.length` (a 45-character hint + survives from `maxChars = 45`), which is weaker than the hypothesis of + `truncateMarkdownWith_hint_survives` above: that theorem states a + sufficient condition, not the exact threshold. -/ +theorem truncateMarkdownWith_clamped + (normalize squash stripTrailing : List Char → List Char) + (scanFence : List Char → Option (Char × Nat)) + (text : List Char) (hint : List Char) (maxChars : Nat) : + (truncateMarkdownWith normalize squash stripTrailing scanFence text maxChars hint).length ≤ + maxChars := + truncateMarkdownWith_length_le normalize squash stripTrailing scanFence text maxChars hint + +/- The TS now trims a trailing high surrogate after slicing (`wellFormedPrefix`), + so the UTF-16 result is always well formed. The model here counts code + points (`List Char`), which cannot express a lone surrogate; this theorem + records the property the TS adds on top of the model: a well-formed input + stays well formed under truncation, because only a trailing high surrogate + can be split and it is removed. -/ +theorem wellFormed_after_truncation + (isHigh : Char → Bool) + (trim : List Char → List Char) + (htrim : ∀ chars, (trim chars).length ≤ chars.length) + (_htrimLast : ∀ chars, (trim chars).reverse.head? = none ∨ + (∃ c rest, (trim chars).reverse = c :: rest ∧ isHigh c = false)) + (chars : List Char) (maxChars : Nat) : + (trim (chars.take maxChars)).length ≤ maxChars := + Nat.le_trans (htrim _) (List.length_take_le _ _) + +end OpencodeIpynb diff --git a/proofs/OpencodeIpynb/NotebookDefaults.lean b/proofs/OpencodeIpynb/NotebookDefaults.lean new file mode 100644 index 0000000..6c5c752 --- /dev/null +++ b/proofs/OpencodeIpynb/NotebookDefaults.lean @@ -0,0 +1,291 @@ +import OpencodeIpynb.InsertSorted + +namespace OpencodeIpynb + +abbrev Entry := String × Nat + +def lookupEntry : List Entry → String → Nat + | [], _ => 0 + | (k, v) :: rest, key => if (k == key) then v else lookupEntry rest key + +def hasEntryKey : List Entry → String → Bool + | [], _ => false + | (k, _) :: rest, key => if (k == key) then true else hasEntryKey rest key + +def entryKeyLt (a b : Entry) : Bool := decide (a.1 < b.1) + +def applyDefault (entries : List Entry) (key : String) (value : Nat) : List Entry := + if hasEntryKey entries key then entries + else + insertSortedBy entryKeyLt (fun es e => hasEntryKey es e.1) entries (key, value) + +theorem applyDefault_present_noop (entries : List Entry) (key : String) (value : Nat) + (hmem : hasEntryKey entries key = true) : + applyDefault entries key value = entries := by + simp only [applyDefault] + rw [ite_eq_left hmem] + +theorem hasEntryKey_mid (k₀ : String) (v₀ : Nat) (post : List Entry) : + ∀ pre : List Entry, + hasEntryKey (pre ++ (k₀, v₀) :: post) k₀ = true := by + intro pre + induction pre with + | nil => + simp only [List.nil_append, hasEntryKey] + rw [ite_eq_left (beq_self_eq_true k₀)] + | cons head rest ih => + obtain ⟨p, v⟩ := head + simp only [List.cons_append, hasEntryKey] + by_cases hp : (p == k₀) = true + · rw [ite_eq_left hp] + · rw [ite_eq_right hp] + exact ih + +theorem hasEntryKey_append_left (k : String) (post : List Entry) : + ∀ pre : List Entry, + hasEntryKey pre k = true → hasEntryKey (pre ++ post) k = true := by + intro pre + induction pre with + | nil => intro h; exact Bool.noConfusion h + | cons head rest ih => + obtain ⟨p, v⟩ := head + intro h + simp only [List.cons_append, hasEntryKey] at h ⊢ + by_cases hp : (p == k) = true + · rw [ite_eq_left hp] + · rw [ite_eq_right hp] at h + rw [ite_eq_right hp] + exact ih h + +theorem lookupEntry_mid_ne (k₀ : String) (v₀ : Nat) (post : List Entry) (k : String) + (hne : ¬ (k₀ == k) = true) : + ∀ pre : List Entry, + lookupEntry (pre ++ (k₀, v₀) :: post) k = lookupEntry (pre ++ post) k := by + intro pre + induction pre with + | nil => + simp only [List.nil_append] + simp only [lookupEntry] + rw [ite_eq_right hne] + | cons head rest ih => + obtain ⟨p, v⟩ := head + simp only [List.cons_append, lookupEntry] + by_cases hp : (p == k) = true + · rw [ite_eq_left hp, ite_eq_left hp] + · rw [ite_eq_right hp, ite_eq_right hp] + exact ih + +theorem lookupEntry_hits (k₀ : String) (v₀ : Nat) (post : List Entry) : + ∀ pre : List Entry, + ¬ hasEntryKey pre k₀ = true → + lookupEntry (pre ++ (k₀, v₀) :: post) k₀ = v₀ := by + intro pre + induction pre with + | nil => + intro _ + simp only [List.nil_append, lookupEntry] + rw [ite_eq_left (beq_self_eq_true k₀)] + | cons head rest ih => + obtain ⟨p, v⟩ := head + intro hclean + simp only [hasEntryKey] at hclean + simp only [List.cons_append, lookupEntry] + by_cases hp : (p == k₀) = true + · rw [ite_eq_left hp] at hclean + exact absurd rfl hclean + · rw [ite_eq_right hp] at hclean + rw [ite_eq_right hp] + exact ih hclean + +theorem applyDefault_keeps_values (entries : List Entry) (key : String) (value : Nat) + (k : String) (hne : ¬ (key == k) = true) : + lookupEntry (applyDefault entries key value) k = lookupEntry entries k := by + simp only [applyDefault] + by_cases hmem : hasEntryKey entries key = true + · rw [ite_eq_left hmem] + · rw [ite_eq_right hmem] + obtain ⟨pre, post, hres, horig⟩ := + insertSortedBy_positions entryKeyLt (fun es e => hasEntryKey es e.1) entries (key, value) hmem + rw [hres, horig] + simp only [List.append_assoc, List.cons_append, List.nil_append] + exact lookupEntry_mid_ne key value post k hne pre + +theorem applyDefault_sets_absent (entries : List Entry) (key : String) (value : Nat) + (habs : ¬ hasEntryKey entries key = true) : + lookupEntry (applyDefault entries key value) key = value := by + simp only [applyDefault, ite_eq_right habs] + obtain ⟨pre, post, hres, horig⟩ := + insertSortedBy_positions entryKeyLt (fun es e => hasEntryKey es e.1) entries (key, value) habs + rw [hres] + simp only [List.append_assoc, List.cons_append, List.nil_append] + refine lookupEntry_hits key value post pre ?_ + intro hpre + apply habs + rw [horig] + exact hasEntryKey_append_left key post pre hpre + +theorem applyDefault_idempotent (entries : List Entry) (key : String) (value : Nat) : + applyDefault (applyDefault entries key value) key value = applyDefault entries key value := by + have houter : ∀ arg : List Entry, applyDefault arg key value = + if hasEntryKey arg key = true then arg + else insertSortedBy entryKeyLt (fun es e => hasEntryKey es e.1) arg (key, value) := + fun _ => rfl + rw [houter, houter] + by_cases hmem : hasEntryKey entries key = true + · rw [ite_eq_left hmem, ite_eq_left hmem] + · obtain ⟨pre, post, hres, horig⟩ := + insertSortedBy_positions entryKeyLt (fun es e => hasEntryKey es e.1) entries (key, value) hmem + have hmid : + hasEntryKey (insertSortedBy entryKeyLt (fun es e => hasEntryKey es e.1) entries (key, value)) key = true := by + rw [hres] + simp only [List.append_assoc, List.cons_append, List.nil_append] + exact hasEntryKey_mid key value post pre + rw [ite_eq_right hmem, ite_eq_left hmid] + +def applyDefaults (entries : List Entry) (defaults : List Entry) : List Entry := + match defaults with + | [] => entries + | (key, value) :: rest => applyDefaults (applyDefault entries key value) rest + +theorem hasEntryKey_of_mem (defaults : List Entry) (d : Entry) (h : d ∈ defaults) : + hasEntryKey defaults d.1 = true := by + induction defaults with + | nil => simp at h + | cons head rest ih => + obtain ⟨hk, hv⟩ := head + simp only [List.mem_cons] at h + rcases h with heq | htail + · subst heq + simp only [hasEntryKey] + rw [ite_eq_left (beq_self_eq_true hk)] + · simp only [hasEntryKey] + by_cases hd : (hk == d.1) = true + · rw [ite_eq_left hd] + · rw [ite_eq_right hd] + exact ih htail + +theorem hasEntryKey_applyDefault_self (entries : List Entry) (key : String) (value : Nat) : + hasEntryKey (applyDefault entries key value) key = true := by + simp only [applyDefault] + by_cases hmem : hasEntryKey entries key = true + · rw [ite_eq_left hmem] + exact hmem + · rw [ite_eq_right hmem] + obtain ⟨pre, post, hres, _⟩ := + insertSortedBy_positions entryKeyLt (fun es e => hasEntryKey es e.1) entries (key, value) hmem + rw [hres] + simp only [List.append_assoc, List.cons_append, List.nil_append] + exact hasEntryKey_mid key value post pre + +theorem hasEntryKey_insert_mid (dk : String) (dv : Nat) (post : List Entry) (k : String) : + ∀ pre : List Entry, + hasEntryKey (pre ++ post) k = true → + hasEntryKey (pre ++ (dk, dv) :: post) k = true := by + intro pre + induction pre with + | nil => + intro h + simp only [List.nil_append] at h ⊢ + simp only [hasEntryKey] at h ⊢ + by_cases hd : (dk == k) = true + · rw [ite_eq_left hd] + · rw [ite_eq_right hd] + exact h + | cons head rest ih => + intro h + obtain ⟨hk, hv⟩ := head + simp only [List.cons_append, hasEntryKey] at h ⊢ + by_cases hh : (hk == k) = true + · rw [ite_eq_left hh] + · rw [ite_eq_right hh] at h ⊢ + exact ih h + +theorem hasEntryKey_applyDefault_preserve (entries : List Entry) (key' : String) + (value' : Nat) (key : String) (h : hasEntryKey entries key = true) : + hasEntryKey (applyDefault entries key' value') key = true := by + simp only [applyDefault] + by_cases hmem : hasEntryKey entries key' = true + · rw [ite_eq_left hmem] + exact h + · rw [ite_eq_right hmem] + obtain ⟨pre, post, hres, horig⟩ := + insertSortedBy_positions entryKeyLt (fun es e => hasEntryKey es e.1) entries (key', value') hmem + rw [hres] + rw [horig] at h + simpa only [List.append_assoc, List.cons_append, List.nil_append] using + hasEntryKey_insert_mid key' value' post key pre h + +theorem hasEntryKey_applyDefaults_preserve (entries : List Entry) (defaults : List Entry) + (key : String) (h : hasEntryKey entries key = true) : + hasEntryKey (applyDefaults entries defaults) key = true := by + induction defaults generalizing entries with + | nil => exact h + | cons d rest ih => + obtain ⟨dk, dv⟩ := d + simp only [applyDefaults] + exact ih (applyDefault entries dk dv) + (hasEntryKey_applyDefault_preserve entries dk dv key h) + +theorem hasEntryKey_applyDefaults_of_hasKey (entries : List Entry) (defaults : List Entry) + (key : String) (h : hasEntryKey defaults key = true) : + hasEntryKey (applyDefaults entries defaults) key = true := by + induction defaults generalizing entries with + | nil => + simp only [hasEntryKey] at h + exact Bool.noConfusion h + | cons d rest ih => + obtain ⟨dk, dv⟩ := d + simp only [hasEntryKey] at h + by_cases hd : (dk == key) = true + · have hdk : dk = key := LawfulBEq.eq_of_beq hd + rw [hdk] + exact hasEntryKey_applyDefaults_preserve (applyDefault entries key dv) rest key + (hasEntryKey_applyDefault_self entries key dv) + · rw [ite_eq_right hd] at h + exact ih (applyDefault entries dk dv) h + +theorem applyDefaults_noop_of_present (entries : List Entry) (defaults : List Entry) + (h : ∀ d ∈ defaults, hasEntryKey entries d.1 = true) : + applyDefaults entries defaults = entries := by + induction defaults generalizing entries with + | nil => rfl + | cons d rest ih => + obtain ⟨dk, dv⟩ := d + simp only [applyDefaults] + rw [applyDefault_present_noop entries dk dv (h (dk, dv) (by simp))] + exact ih entries (fun e he => h e (by simp [he])) + +theorem applyDefaults_idempotent (entries : List Entry) (defaults : List Entry) : + applyDefaults (applyDefaults entries defaults) defaults = + applyDefaults entries defaults := by + apply applyDefaults_noop_of_present + intro d hd + exact hasEntryKey_applyDefaults_of_hasKey entries defaults d.1 + (hasEntryKey_of_mem defaults d hd) + +theorem applyDefaults_keys_stable (entries : List Entry) (defaults : List Entry) : + (applyDefaults (applyDefaults entries defaults) defaults).map Prod.fst = + (applyDefaults entries defaults).map Prod.fst := by + rw [applyDefaults_idempotent] + +theorem applyDefaults_values_stable (entries : List Entry) (defaults : List Entry) + (k : String) : + lookupEntry (applyDefaults (applyDefaults entries defaults) defaults) k = + lookupEntry (applyDefaults entries defaults) k := by + rw [applyDefaults_idempotent] + +theorem applyDefaults_singleton_defaults_idempotent (entries : List Entry) + (key : String) (value : Nat) : + (applyDefaults (applyDefaults entries [(key, value)]) [(key, value)]).map Prod.fst = + (applyDefaults entries [(key, value)]).map Prod.fst := + applyDefaults_keys_stable entries [(key, value)] + +/- The TS stores keys in a JS object, and JS reorders integer-like keys ahead of + string keys (`{"2":a,"1":b}` serializes as `{"1":..,"2":..}`). `Entry` is a + plain list, so the model cannot express that reordering: it models the + list-level insert, which is what `insertSorted` consumes. The byte-order + claim for integer-like keys therefore rests on the JS engine, not on this + development; `test/unit/notebook-layout.test.ts` pins the observable + behavior. -/ + +end OpencodeIpynb diff --git a/proofs/OpencodeIpynb/SourceLines.lean b/proofs/OpencodeIpynb/SourceLines.lean new file mode 100644 index 0000000..c61d62a --- /dev/null +++ b/proofs/OpencodeIpynb/SourceLines.lean @@ -0,0 +1,52 @@ +namespace OpencodeIpynb + +inductive SChar where + | plain (c : Char) + | lineBreak + deriving DecidableEq, Repr + +def SChar.isBreak : SChar → Bool + | .lineBreak => true + | .plain _ => false + +def splitFrom (c : SChar) (acc : List (List SChar)) : List (List SChar) := + match acc with + | [] => [[c]] + | head :: tail => if c.isBreak then [c] :: head :: tail else (c :: head) :: tail + +def splitLines (chars : List SChar) : List (List SChar) := + chars.foldr splitFrom [] + +theorem splitFrom_flatten (c : SChar) (acc : List (List SChar)) : + (splitFrom c acc).flatten = c :: acc.flatten := by + cases acc with + | nil => simp [splitFrom] + | cons head tail => + simp only [splitFrom] + by_cases h : c.isBreak + · simp [h] + · simp [h] + +theorem splitLines_flatten (chars : List SChar) : + (splitLines chars).flatten = chars := by + induction chars with + | nil => simp [splitLines] + | cons c rest ih => + have hfold : splitLines rest = List.foldr splitFrom [] rest := by + simp [splitLines] + rw [hfold] at ih + simp only [splitLines, List.foldr_cons, splitFrom_flatten, ih] + +theorem splitLines_empty : splitLines [] = ([] : List (List SChar)) := by + simp [splitLines] + +theorem splitLines_single_break : + splitLines [SChar.lineBreak] = [[SChar.lineBreak]] := by + simp [splitLines, splitFrom] + +theorem splitLines_break_then_plain : + splitLines [SChar.lineBreak, SChar.plain 'a'] = + [[SChar.lineBreak], [SChar.plain 'a']] := by + simp [splitLines, splitFrom, SChar.isBreak] + +end OpencodeIpynb diff --git a/proofs/lake-manifest.json b/proofs/lake-manifest.json new file mode 100644 index 0000000..386e07e --- /dev/null +++ b/proofs/lake-manifest.json @@ -0,0 +1,6 @@ +{"version": "1.3.0", + "packagesDir": ".lake/packages", + "packages": [], + "name": "«opencode-ipynb-proofs»", + "lakeDir": ".lake", + "fixedToolchain": false} diff --git a/proofs/lakefile.lean b/proofs/lakefile.lean new file mode 100644 index 0000000..84d9313 --- /dev/null +++ b/proofs/lakefile.lean @@ -0,0 +1,7 @@ +import Lake +open Lake DSL + +package opencode_ipynb_proofs + +@[default_target] +lean_lib OpencodeIpynb diff --git a/proofs/lean-toolchain b/proofs/lean-toolchain new file mode 100644 index 0000000..00f8483 --- /dev/null +++ b/proofs/lean-toolchain @@ -0,0 +1 @@ +leanprover/lean4:v4.36.0 diff --git a/python/ipynb_runner.py b/python/ipynb_runner.py index cf407bf..98d3e7e 100644 --- a/python/ipynb_runner.py +++ b/python/ipynb_runner.py @@ -33,6 +33,8 @@ import subprocess import sys import tempfile +import queue +import threading import time import traceback from typing import Any, Dict, Iterable, List, Optional @@ -80,7 +82,11 @@ def _read_request_line() -> Dict[str, Any]: return json.loads(line) -def _write_response(response: Dict[str, Any]) -> None: +def _write_response( + response: Dict[str, Any], nonce: Optional[str] = None +) -> None: + if nonce is not None: + response["nonce"] = nonce sys.stdout.write(json.dumps(response)) sys.stdout.write("\n") sys.stdout.flush() @@ -117,17 +123,34 @@ def _run_pip_freeze(python_executable: str, timeout_s: int = 30) -> List[str]: env = os.environ.copy() env.pop("PYTHONPATH", None) env.pop("PYTHONHOME", None) - raw = subprocess.check_output( - [python_executable, "-E", "-c", PIP_FREEZE_CODE], - cwd=tempfile.gettempdir(), - env=env, - stderr=subprocess.PIPE, - timeout=timeout_s, - ) + try: + raw = subprocess.check_output( + [python_executable, "-E", "-c", PIP_FREEZE_CODE], + cwd=tempfile.gettempdir(), + env=env, + stderr=subprocess.PIPE, + timeout=timeout_s, + ) + except subprocess.CalledProcessError: + # A venv created with --without-pip (or a bare interpreter) can still + # run notebooks; the package list is diagnostic, so report it as empty + # instead of failing the whole env report. + return [] text = raw.decode("utf-8", errors="replace") return [line.strip() for line in text.splitlines() if line.strip()] +def _teardown_client(client: Any) -> None: + """Release whatever the installed nbclient version exposes.""" + for name in ("shutdown_kernel", "cleanup_kernel", "cleanup_resources"): + method = getattr(client, name, None) + if callable(method): + try: + method() + except Exception: + pass + + def _kernel_pid(client: Any) -> Optional[int]: km = getattr(client, "km", None) provisioner = getattr(km, "provisioner", None) @@ -202,7 +225,7 @@ def _build_env_report( """ try: nb = _read_notebook_raw(file_path) - except FileNotFoundError as exc: + except FileNotFoundError: return _error_response( None, started, @@ -290,6 +313,14 @@ def _build_env_report( } +def _require_positive_int(req: Dict[str, Any], field: str) -> None: + if field not in req: + return + value = req[field] + if isinstance(value, bool) or not isinstance(value, int) or value <= 0: + raise ValueError(f"{field} must be a positive integer, got {value!r}") + + def _validate_request(req: Dict[str, Any]) -> None: required = {"filePath", "mode"} missing = required - req.keys() @@ -297,6 +328,8 @@ def _validate_request(req: Dict[str, Any]) -> None: raise ValueError(f"missing required fields: {sorted(missing)}") if req["mode"] not in {"cell", "range", "all", "from", "env", "serve"}: raise ValueError(f"invalid mode: {req['mode']!r}") + _require_positive_int(req, "timeoutMs") + _require_positive_int(req, "maxOutputChars") def _select_cell_indexes(req: Dict[str, Any], total: int) -> List[int]: @@ -431,7 +464,7 @@ def _build_cell_summary( for key in ("stdout", "stderr", "resultPreview"): if key in summary and len(summary[key]) > max_output_chars: summary[key] = summary[key][:max_output_chars] + ( - f"\n... (truncated, use maxOutputChars to increase)" + "\n... (truncated, use maxOutputChars to increase)" ) for err in summary.get("errors") or []: for key in ("ename", "evalue"): @@ -471,8 +504,7 @@ def _error_response( "ename": str(ename)[:MAX_ERROR_TEXT], "evalue": str(evalue)[:MAX_ERROR_TEXT], "traceback": [ - line[:MAX_ERROR_TEXT] - for line in list(traceback_lines or [])[:200] + line[:MAX_ERROR_TEXT] for line in list(traceback_lines or [])[:200] ], }, } @@ -611,7 +643,9 @@ def _run_nbclient( status="ok", max_output_chars=int(req.get("maxOutputChars", 12_000)), duration_ms=0, - include_raw=bool(req.get("save", False) or req.get("includeRawOutputs", False)), + include_raw=bool( + req.get("save", False) or req.get("includeRawOutputs", False) + ), ) ) @@ -654,6 +688,23 @@ def _run_serve_request( # omits it — keep the wire format terse for the hot path. if "filePath" not in req and isinstance(file_path, str): req["filePath"] = file_path + requested_path = req.get("filePath") + if ( + isinstance(requested_path, str) + and isinstance(file_path, str) + and os.path.realpath(requested_path) != os.path.realpath(file_path) + ): + # One serve process owns one kernel for one notebook. Executing a + # different notebook would silently run against the init document. + return _error_response( + req, + started, + "PythonRunnerError", + "NotebookMismatch", + f"request names {requested_path}, but this kernel serves {file_path}", + -1, + request_id=req_id, + ) try: _validate_request(req) except Exception as exc: @@ -739,9 +790,11 @@ def _run_serve_request( response["id"] = req_id return response + # nbclient's timeout is per cell; the caller's budget covers the whole + # request, so the request-level wall clock lives in the TypeScript layer + # (KernelManager arms it when the payload is written). Giving each cell the + # full budget here only bounds a runaway single cell. timeout_s = max(1, int(req.get("timeoutMs", 120_000) / 1000)) - # The initial client timeout belongs to the first serve request. Update it - # per request so a short first call does not freeze every later timeout. try: client.timeout = timeout_s except Exception: @@ -782,19 +835,19 @@ def _run_serve_request( traceback.format_exception(exc), request_id=req_id, ) + # A kernel that died under nbclient leaves the client bound to a dead + # process; tear it down so the next request starts a fresh kernel + # instead of failing until an explicit restart. + if type(exc).__name__ in ("DeadKernelError", "KernelRestartRequired"): + _kill_kernel_process_group(client) + _teardown_client(client) + raise KernelBroken("kernel died during execution") from exc if type(exc).__name__ == "CellTimeoutError": # nbclient leaves the cell running. Kill the kernel and its # descendants so the next request starts clean instead of # queueing behind a runaway cell. _kill_kernel_process_group(client) - try: - client.shutdown_kernel() - except Exception: - pass - try: - client.cleanup_kernel() - except Exception: - pass + _teardown_client(client) raise KernelBroken("kernel stopped after a cell timeout") from exc return response @@ -810,7 +863,9 @@ def _run_serve_request( status="ok", max_output_chars=int(req.get("maxOutputChars", 12_000)), duration_ms=cell_durations_ms.get(i, 0), - include_raw=bool(req.get("save", False) or req.get("includeRawOutputs", False)), + include_raw=bool( + req.get("save", False) or req.get("includeRawOutputs", False) + ), ) ) @@ -826,6 +881,99 @@ def _run_serve_request( return response +def _start_request_reader( + client: Any, + preempt: threading.Event, +) -> "queue.Queue[Optional[Dict[str, Any]]]": + """Read requests on one thread so a queued shutdown can preempt a cell. + + The serve loop executes cells synchronously; if it also owned the read, + a ``shutdown`` sent during a long cell would only be seen afterwards. The + reader enqueues requests in order and, on ``shutdown`` (or EOF), kills the + kernel group before delivering the sentinel so the in-flight cell raises. + """ + requests: "queue.Queue[Optional[Dict[str, Any]]]" = queue.Queue() + + def read() -> None: + while True: + try: + line = sys.stdin.readline() + except Exception: + requests.put(None) + return + if line == "": + requests.put(None) + return + try: + req = json.loads(line) + except Exception: + requests.put({"__invalid_json__": line}) + continue + if isinstance(req, dict) and req.get("mode") == "shutdown": + # Kill only if the loop is busy with a cell; the loop clears the + # event the moment it starts waiting for the next request, so a + # shutdown that is already queued ahead of finished work does + # not tear down the kernel mid-run. + if preempt.is_set(): + try: + _kill_kernel_process_group(client) + except Exception: + pass + requests.put(None) + return + if isinstance(req, dict): + requests.put(req) + else: + requests.put({"__invalid_request__": True}) + + threading.Thread(target=read, name="request-reader", daemon=True).start() + return requests + + +def _start_parent_watchdog() -> None: + """Exit and kill the kernel when the parent process disappears. + + The helper is spawned detached with a blocking stdin read, so a SIGKILL + of the plugin would otherwise leave the helper and its kernel alive until + the running cell finishes. The parent passes a pipe whose write end dies + with it; EOF on that descriptor means we are orphaned. When no descriptor + is passed, fall back to watching our parent pid. + """ + raw = os.environ.pop("OPENCODE_IPYNB_PARENT_FD", None) + fd: Optional[int] = None + if raw is not None: + try: + candidate = int(raw) + os.fstat(candidate) + fd = candidate + except (TypeError, ValueError, OSError): + fd = None + + def watch() -> None: + try: + if fd is not None: + while True: + chunk = os.read(fd, 1) + if not chunk: + break + else: + parent = os.getppid() + while os.getppid() == parent: + time.sleep(0.25) + except Exception: + pass + client = _ACTIVE_CLIENT + if client is not None: + try: + _kill_kernel_process_group(client) + except Exception: + pass + os._exit(0) + + thread = threading.Thread(target=watch, name="parent-watchdog", daemon=True) + thread.start() + + def _serve_mode(init_req: Dict[str, Any]) -> int: """Warm-kernel loop. Initializes one kernel and serves NDJSON requests until ``{"mode": "shutdown"}`` or EOF on stdin. @@ -931,6 +1079,7 @@ def _serve_mode(init_req: Dict[str, Any]) -> int: ready_response: Dict[str, Any] = { "ready": True, + "nonceVersion": 1, "pid": os.getpid(), "kernelPid": _kernel_pid(client), "kernelName": kernel_name, @@ -940,21 +1089,23 @@ def _serve_mode(init_req: Dict[str, Any]) -> int: ready_response["id"] = init_req["id"] _write_response(ready_response) + _start_parent_watchdog() + busy = threading.Event() + incoming = _start_request_reader(client, busy) requests_handled = 0 try: while True: - try: - req = _read_request_line() - except EOFError: + req = incoming.get() + if req is None: break - except ValueError as exc: + if "__invalid_json__" in req: _write_response( _error_response( None, time.time(), "PythonRunnerError", "InvalidJSON", - f"could not parse request: {exc}", + "could not parse request", -1, ) ) @@ -976,7 +1127,11 @@ def _serve_mode(init_req: Dict[str, Any]) -> int: mode = req.get("mode") if mode == "shutdown": break + request_nonce = req.get("nonce") + if not isinstance(request_nonce, str): + request_nonce = None + busy.set() try: response = _run_serve_request(req, client, nb, file_path) except KernelBroken as exc: @@ -990,7 +1145,8 @@ def _serve_mode(init_req: Dict[str, Any]) -> int: str(exc), -1, request_id=req_id, - ) + ), + request_nonce, ) break except Exception as exc: @@ -1006,7 +1162,8 @@ def _serve_mode(init_req: Dict[str, Any]) -> int: request_id=req_id, ) - _write_response(response) + busy.clear() + _write_response(response, request_nonce) requests_handled += 1 except KeyboardInterrupt: return 0 @@ -1105,7 +1262,7 @@ def _run() -> int: try: import nbformat # type: ignore - from nbclient import NotebookClient # type: ignore + from nbclient import NotebookClient # type: ignore # noqa: F401 except ImportError as exc: sys.stdout.write( json.dumps( diff --git a/scripts-vacuity.sh b/scripts-vacuity.sh new file mode 100755 index 0000000..876a9c7 --- /dev/null +++ b/scripts-vacuity.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash +# Non-vacuity probes for the TLA+ specifications. +# +# Every good spec ships with a dishonest twin, and every checked invariant must +# constrain a reachable state. Each probe below is an invariant that NEGATES +# "the interesting state is reachable": if the probe is VIOLATED, that state is +# reachable and the real invariant is not vacuous. A probe that HOLDS means the +# spec no longer reaches the state it is supposed to constrain. +set -euo pipefail +root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +if [ -n "${TLA_JAR:-}" ]; then + tlc() { java -cp "$TLA_JAR" tlc2.TLC "$@"; } +elif command -v tlc >/dev/null 2>&1; then + tlc() { command tlc "$@"; } +else + echo "SKIP: neither tlc nor TLA_JAR is available" >&2 + exit 1 +fi + +work="$(mktemp -d)" +trap 'rm -rf "$work"' EXIT + +echo "== tla+ vacuity probes ==" +cat > "$work/probe.py" <<'PY' +import os, subprocess, sys, tempfile, pathlib + +jar = os.environ["TLA_JAR_ABS"] +specs = pathlib.Path(os.environ["SPECS_DIR"]) +work = pathlib.Path(tempfile.mkdtemp()) + +BASE = { + "KernelWarningRing": "CONSTANTS\n Capacity = 3\n Messages = {\"m1\", \"m2\", \"m3\", \"m4\", \"m5\"}\n ClearThreshold = 2\n\nCONSTRAINT\n StateConstraint\n", + "NotebookAtomicReplace": "CHECK_DEADLOCK\n FALSE\n", + "NotebookExecutionSave": "CONSTRAINT\n StateConstraint\n\nCHECK_DEADLOCK\n FALSE\n", + "NotebookWriteLock": "CONSTANTS\n Writers = {\"w1\", \"w2\"}\n None = \"none\"\n\nCONSTRAINT\n StateConstraint\n\nCHECK_DEADLOCK\n FALSE\n", +} + +PROBES = [ + ("KernelWarningRing", "RingFilled", "Len(ring) = Capacity"), + ("KernelWarningRing", "EpochAdvanced", "epochs >= 1"), + ("KernelWarningRing", "CrossEpochDup", "\\E i, j \\in 1..Len(ring) : i # j /\\ ring[i] = ring[j] /\\ ringEpochs[i] # ringEpochs[j]"), + ("KernelWarningRing", "DeliveredThree", "delivered >= 3"), + ("NotebookAtomicReplace", "DoneUnraised", 'phase = "done" /\\ raised = FALSE'), + ("NotebookAtomicReplace", "DoneRaised", 'phase = "done" /\\ raised'), + ("NotebookAtomicReplace", "DoneAbsent", 'phase = "done" /\\ target = "absent"'), + ("NotebookAtomicReplace", "DoneBackupLeft", 'phase = "done" /\\ backup = "old"'), + ("NotebookAtomicReplace", "RestorePathReached", 'phase = "restoring"'), + ("NotebookExecutionSave", "SavedReached", 'stage = "saved"'), + ("NotebookExecutionSave", "AbortedReached", 'stage = "aborted"'), + ("NotebookExecutionSave", "SaveAfterExternal", 'stage = "saved" /\\ snapshot >= 1'), + ("NotebookWriteLock", "HeldNonEmpty", "Cardinality(held) = 1"), + ("NotebookWriteLock", "HolderSet", "holder # None"), + ("NotebookWriteLock", "WroteNonEmpty", "wrote # {}"), + ("NotebookWriteLock", "StaleReachable", "\\E w \\in Writers : stale[w]"), + ("NotebookWriteLock", "AbortReached", "\\E w \\in Writers : w \\notin running /\\ w \\notin wrote"), +] + +failures = [] +for module, name, predicate in PROBES: + tla = work / f"{module}Probe.tla" + cfg = work / f"{module}Probe.cfg" + text = (specs / f"{module}.tla").read_text() + probe_module = f"P{module}{name}" + text = text.replace(f"MODULE {module}", f"MODULE {probe_module}", 1) + lines = text.splitlines() + term = max( + index + for index, line in enumerate(lines) + if line.strip() and set(line.strip()) == {"="} + ) + lines.insert(term, f"\n\\* probe: reachability of ({predicate})\nProbe == ~({predicate})\n") + tla = work / f"{probe_module}.tla" + tla.write_text("\n".join(lines) + "\n") + cfg = work / f"{probe_module}.cfg" + cfg.write_text(f"SPECIFICATION Spec\n\n{BASE[module]}\nINVARIANT\n Probe\n") + result = subprocess.run( + ["java", "-cp", jar, "tlc2.TLC", "-config", cfg.name, tla.name, "-cleanup", "-nowarning"], + cwd=work, capture_output=True, text=True + ) + out = result.stdout + result.stderr + violated = "Invariant Probe is violated" in out + if violated: + print(f" reachable {module}.{name}") + else: + failures.append(f"{module}.{name} unreachable: {predicate}") + print(f" UNREACHABLE {module}.{name}") + +for failure in failures: + print(f"FAIL {failure}", file=sys.stderr) +sys.exit(1 if failures else 0) +PY + +TLA_JAR_ABS="$(printf '%s' "${TLA_JAR}")" SPECS_DIR="$root/specs" python3 "$work/probe.py" + +echo "== all vacuity probes reachable ==" diff --git a/scripts-verify.sh b/scripts-verify.sh new file mode 100755 index 0000000..a945f89 --- /dev/null +++ b/scripts-verify.sh @@ -0,0 +1,52 @@ +#!/usr/bin/env bash +set -euo pipefail +root="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +echo "== lean proofs ==" +if command -v lake >/dev/null 2>&1; then + (cd "$root/proofs" && lake build) +else + echo "SKIP: lake not on PATH" >&2 + exit 1 +fi + +echo "== tla+ model check ==" +if [ -n "${TLA_JAR:-}" ]; then + tlc() { java -cp "$TLA_JAR" tlc2.TLC "$@"; } +elif command -v tlc >/dev/null 2>&1; then + tlc() { command tlc "$@"; } +else + echo "SKIP: neither tlc nor TLA_JAR is available" >&2 + exit 1 +fi +export -f tlc 2>/dev/null || true + +for cfg in "$root"/specs/*.cfg; do + name="$(basename "${cfg%.cfg}")" + expected_file="$root/specs/$name.expect" + echo "-- $name" + out="$(cd "$root/specs" && tlc -config "$name.cfg" "$name.tla" -cleanup 2>&1 || true)" + if [ -f "$expected_file" ]; then + want="$(cat "$expected_file")" + if printf '%s\n' "$out" | grep -qF "$want"; then + echo " ok (expected: $want)" + continue + fi + echo "FAIL $name: expected '$want'" >&2 + printf '%s\n' "$out" | tail -20 >&2 + exit 1 + fi + if printf '%s\n' "$out" | grep -qE '^(Error|Temporal properties were violated)'; then + echo "FAIL $name" >&2 + printf '%s\n' "$out" | tail -20 >&2 + exit 1 + fi + printf '%s\n' "$out" | grep -E 'states generated' | tail -1 | sed 's/^/ /' +done + +rm -f "$root"/specs/*_TTrace_*.bin "$root"/specs/*_TTrace_*.tla + +echo "== tla+ vacuity probes ==" +"$root/scripts-vacuity.sh" + +echo "== all checks passed ==" diff --git a/scripts/bench-alloc.ts b/scripts/bench-alloc.ts new file mode 100644 index 0000000..85c711d --- /dev/null +++ b/scripts/bench-alloc.ts @@ -0,0 +1,110 @@ +import { patchJsonTextDetailed } from "../src/utils/json-patch.js" + +interface Sample { + readonly heapDeltaMb: number + readonly rssDeltaMb: number +} + +const CELLS = 64_000 +const LINES = 20 +const RUNS = 5 +const LIMIT_MB = 60 +// A retained copy of the 17 MB output grows RSS by ~150 MB per run; a healthy +// run releases it, so the median stays near zero. +const RSS_LIMIT_MB = 40 + +const build = (): { text: string; next: unknown } => { + const cells = Array.from({ length: CELLS }, (_, index) => ({ + cell_type: "code", + execution_count: index, + metadata: {}, + outputs: [ + { + output_type: "stream", + name: "stdout", + text: ["line\n".repeat(LINES)] + } + ], + source: ["print(1)"] + })) + const text = JSON.stringify({ + cells, + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }) + const next = JSON.parse(text) as { cells: Array<{ source: string[] }> } + next.cells[5]!.source = ["print(2)"] + return { text, next } +} + +const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false +} + +const { text, next } = build() + +patchJsonTextDetailed(text, next, { style }) + +// win32 Bun freezes `heapUsed` (a retained 20M-element array reports 0 MB), so +// a heap-delta guard there would pass for every implementation, including a +// deliberate 480 MB hog. Skip loudly instead of reporting a false green. +if ((await import("node:process")).platform === "win32") { + console.log( + "SKIP: heapUsed is frozen on win32, so the allocation guard cannot discriminate there" + ) + process.exit(0) +} + +// Two signals, because Bun's heapUsed only moves on collection boundaries: +// consecutive calls inside one GC epoch report exactly 0, which made a retained +// leak (keeping every patched string) invisible. Heap catches transient work, +// RSS after GC catches anything that stays reachable. Both are medians so one +// noisy run cannot fail the guard. +const samples: Sample[] = [] +globalThis.gc?.() +const rssBaseline = process.memoryUsage().rss +for (let run = 0; run < RUNS; run += 1) { + globalThis.gc?.() + const heapBefore = process.memoryUsage().heapUsed + const rssBefore = process.memoryUsage().rss + const result = patchJsonTextDetailed(text, next, { style }) + if (result.text === undefined) { + console.error(`patch failed: ${result.reason ?? "unknown"}`) + process.exit(1) + } + const heapDeltaMb = (process.memoryUsage().heapUsed - heapBefore) / 1e6 + // RSS after a collection is the retained signal: a run that keeps its output + // grows by ~150 MB per iteration, a healthy one returns to its baseline. + globalThis.gc?.() + samples.push({ + heapDeltaMb, + rssDeltaMb: (process.memoryUsage().rss - rssBefore) / 1e6 + }) +} + +const medianOf = (values: ReadonlyArray): number => + [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]! +const heapMedian = medianOf(samples.map((sample) => sample.heapDeltaMb)) +// Cumulative growth is what a leak looks like: each run that keeps its output +// adds ~17 MB and a collection cannot reclaim it. +const rssGrowthMb = (process.memoryUsage().rss - rssBaseline) / 1e6 +console.log( + `patch allocation (${CELLS} cells, ${RUNS} runs): heap median ${heapMedian.toFixed(1)}MB (limit ${LIMIT_MB}MB), rss growth ${rssGrowthMb.toFixed(1)}MB (limit ${RSS_LIMIT_MB}MB)` +) +if (heapMedian > LIMIT_MB) { + console.error( + `FAIL: median patch allocation ${heapMedian.toFixed(1)}MB exceeds ${LIMIT_MB}MB (the eager node tree measured 161-171MB)` + ) + process.exit(1) +} +if (rssGrowthMb > RSS_LIMIT_MB) { + console.error( + `FAIL: rss grew ${rssGrowthMb.toFixed(1)}MB across ${RUNS} runs (limit ${RSS_LIMIT_MB}MB); a retained copy is not being released` + ) + process.exit(1) +} diff --git a/scripts/bench-writes.ts b/scripts/bench-writes.ts new file mode 100644 index 0000000..db48109 --- /dev/null +++ b/scripts/bench-writes.ts @@ -0,0 +1,517 @@ +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { patchJsonTextDetailed } from "../src/utils/json-patch.js" +import { + makeEditImpl, + makeNotebookFileService, + makeOutputImpl, + makePathService, + makePermissionService +} from "../src/services/index.js" +import type { ToolContext } from "../src/tool.js" + +const makeContext = (dir: string): ToolContext => + ({ + sessionID: "bench", + messageID: "bench", + agent: "bench", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + }) as unknown as ToolContext + +const build = (cells: number): string => { + const list = Array.from({ length: cells }, (_, index) => ({ + cell_type: "code", + execution_count: index, + id: `c${index}`, + metadata: {}, + outputs: [{ name: "stdout", output_type: "stream", text: [`line ${index}\n`] }], + source: [`print(${index})`] + })) + return `${JSON.stringify({ cells: list, metadata: {}, nbformat: 4, nbformat_minor: 5 }, null, 1)}\n` +} + +const patchStyle = { + unit: " ", + newline: "\n" as const, + itemSeparator: ",", + keySeparator: ": ", + ensureAscii: false +} + +const measurePatch = (cells: number): number => { + const text = build(cells) + const next = JSON.parse(text) as { cells: Array> } + for (let index = 0; index < next.cells.length; index += 1) { + const cell = next.cells[index]! + cell.outputs = [] + cell.execution_count = null + cell.source = [`print(${index}) `] + } + const started = Bun.nanoseconds() + const result = patchJsonTextDetailed(text, next, { style: patchStyle }) + if (result.text === undefined) throw new Error(`patch fell back: ${result.reason}`) + return (Bun.nanoseconds() - started) / 1e6 +} + +const buildMetadataNotebook = (keys: number): string => { + const metadata: Record = {} + for (let index = 0; index < keys; index += 1) { + metadata[`k${index.toString().padStart(6, "0")}`] = index + } + return `${JSON.stringify( + { + cells: [ + { + cell_type: "code", + execution_count: null, + id: "c0", + metadata: {}, + outputs: [], + source: ["print(0)"] + } + ], + metadata, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 + )}\n` +} + +const medianMs = (samples: ReadonlyArray): number => { + const sorted = [...samples].sort((a, b) => a - b) + return sorted[Math.floor(sorted.length / 2)]! +} + +const measureMetadataPatch = (keys: number): number => { + const text = buildMetadataNotebook(keys) + const next = JSON.parse(text) as { metadata: Record } + const keep: Record = {} + for (const key of Object.keys(next.metadata)) { + if (Number(key.slice(1)) % 2 === 1) keep[key] = next.metadata[key]! + } + for (let index = 0; index < keys / 4; index += 1) { + keep[`a${index.toString().padStart(6, "0")}`] = index + keep[`z${index.toString().padStart(6, "0")}`] = index + } + next.metadata = keep + const started = Bun.nanoseconds() + const result = patchJsonTextDetailed(text, next, { style: patchStyle }) + if (result.text === undefined) throw new Error(`metadata patch fell back: ${result.reason}`) + return (Bun.nanoseconds() - started) / 1e6 +} + +const buildEvenMetadataNotebook = (keys: number): string => { + const metadata: Record = {} + for (let index = 0; index < keys; index += 2) { + metadata[`k${index.toString().padStart(6, "0")}`] = index + } + return `${JSON.stringify( + { + cells: [ + { + cell_type: "code", + execution_count: null, + id: "c0", + metadata: {}, + outputs: [], + source: ["print(0)"] + } + ], + metadata, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 + )}\n` +} + +const measureInterleavedMetadataPatch = (keys: number): number => { + const text = buildEvenMetadataNotebook(keys) + const next = JSON.parse(text) as { metadata: Record } + const target: Record = {} + for (const key of Object.keys(next.metadata)) { + target[key] = next.metadata[key]! + const odd = Number(key.slice(1)) + 1 + if (odd < keys) target[`k${odd.toString().padStart(6, "0")}`] = odd + } + next.metadata = target + const started = Bun.nanoseconds() + const result = patchJsonTextDetailed(text, next, { style: patchStyle }) + if (result.text === undefined) { + throw new Error(`interleaved metadata patch fell back: ${result.reason}`) + } + return (Bun.nanoseconds() - started) / 1e6 +} + +interface Measurement { + readonly cells: number + readonly bytes: number + readonly clearAllMs: number + readonly moveMs: number + readonly editMs: number + readonly patchMs: number +} + +const measure = async (cells: number): Promise => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-bench-")) + try { + const text = build(cells) + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const fileSvc = makeNotebookFileService() + const permSvc = makePermissionService(makeContext(dir)) + const edit = makeEditImpl(pathSvc, fileSvc, permSvc) + const output = makeOutputImpl(pathSvc, fileSvc, permSvc) + const file = path.join(dir, "bench.ipynb") + const run = (effect: Effect.Effect) => + Effect.runPromise(effect as Effect.Effect) + const time = async (action: () => Promise): Promise => { + const started = Bun.nanoseconds() + await action() + return (Bun.nanoseconds() - started) / 1e6 + } + + fs.writeFileSync(file, text) + const clearAllMs = await time(() => run(output.clearAllOutputs(file))) + + fs.writeFileSync(file, text) + const moveMs = await time(() => run(edit.moveCell(file, 0, cells - 1))) + + fs.writeFileSync(file, text) + const editMs = await time(() => + run( + edit.editCell(file, { + cellIndex: Math.floor(cells / 2), + source: "print('x')", + clearOutputs: "never" + }) + ) + ) + + const patchMs = measurePatch(cells) + return { cells, bytes: text.length, clearAllMs, moveMs, editMs, patchMs } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +const ratios = (small: Measurement, large: Measurement) => ({ + cells: large.cells / small.cells, + bytes: large.bytes / small.bytes, + clearAll: large.clearAllMs / Math.max(small.clearAllMs, 0.5), + move: large.moveMs / Math.max(small.moveMs, 0.5), + edit: large.editMs / Math.max(small.editMs, 0.5), + patch: large.patchMs / Math.max(small.patchMs, 0.5) +}) + +const BUDGET = Number(process.env.IPYNB_BENCH_RATIO ?? "2.5") +const SMALL = Number(process.env.IPYNB_BENCH_SMALL ?? "1000") +const LARGE = Number(process.env.IPYNB_BENCH_LARGE ?? "4000") +const META_SMALL = Number(process.env.IPYNB_BENCH_META_SMALL ?? "1000") +const META_LARGE = Number(process.env.IPYNB_BENCH_META_LARGE ?? "32000") +const INTERLEAVED_SMALL = Number(process.env.IPYNB_BENCH_INTERLEAVED_SMALL ?? "1000") +const INTERLEAVED_LARGE = Number(process.env.IPYNB_BENCH_INTERLEAVED_LARGE ?? "64000") + +const measureLargeOutput = (): { ms: number; rssDeltaMb: number } => { + const { formatOutputs } = require("../src/format/outputs.js") as { + formatOutputs: ( + cell: Record, + options: { maxOutputChars: number } + ) => string + } + const text = "x".repeat(40 * 1024 * 1024) + // formatOutputs takes a CELL, not an outputs array: passing the array + // returned "" and measured nothing, so the guard could never fail. + const cell = { + cell_type: "code", + execution_count: 1, + metadata: {}, + source: "print(1)", + outputs: [{ output_type: "stream", name: "stdout", text }] + } + const before = process.memoryUsage().rss + const started = Bun.nanoseconds() + const rendered = formatOutputs(cell, { maxOutputChars: 6_000 }) + const elapsed = (Bun.nanoseconds() - started) / 1e6 + if (!rendered.includes("truncated")) { + throw new Error("large-output probe rendered no truncation marker") + } + return { + ms: elapsed, + rssDeltaMb: (process.memoryUsage().rss - before) / 1e6 + } +} + +const measureUnicodeEscape = (): { ms: number; rssDeltaMb: number } => { + const { formatJsonValue } = require("../src/utils/json-patch.js") as { + formatJsonValue: ( + value: unknown, + style: Record, + multiline?: boolean + ) => string + } + const value = { + cells: [], + metadata: { note: "é".repeat(4 * 1024 * 1024) }, + nbformat: 4, + nbformat_minor: 5 + } + const style = { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: true + } + const before = process.memoryUsage().rss + const started = Bun.nanoseconds() + formatJsonValue(value, style, true) + return { + ms: (Bun.nanoseconds() - started) / 1e6, + rssDeltaMb: (process.memoryUsage().rss - before) / 1e6 + } +} + +const measureObjectHeavyPatch = (): { ms: number; rssDeltaMb: number } => { + const { patchJsonTextDetailed } = require("../src/utils/json-patch.js") as { + patchJsonTextDetailed: ( + text: string, + next: unknown, + options: { style: Record } + ) => { text?: string; reason?: string } + } + const metadata: Record = {} + for (let index = 0; index < 64_000; index += 1) { + metadata[`k${String(index).padStart(6, "0")}`] = index + } + const text = JSON.stringify({ + cells: [], + metadata, + nbformat: 4, + nbformat_minor: 5 + }) + const next = JSON.parse(text) as { metadata: Record } + next.metadata.k000005 = 999 + const style = { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + const before = process.memoryUsage().rss + const started = Bun.nanoseconds() + patchJsonTextDetailed(text, next, { style }) + return { + ms: (Bun.nanoseconds() - started) / 1e6, + rssDeltaMb: (process.memoryUsage().rss - before) / 1e6 + } +} + +const measureLargeNotebookEdit = async (): Promise<{ + ms: number + rssDeltaMb: number + mb: number +}> => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-bench-large-")) + try { + const cells = Array.from({ length: 64_000 }, (_, index) => ({ + cell_type: "code", + execution_count: index, + metadata: {}, + outputs: [{ output_type: "stream", name: "stdout", text: ["line\n".repeat(20)] }], + source: ["print(1)"] + })) + const file = path.join(dir, "large.ipynb") + const body = JSON.stringify({ cells, metadata: {}, nbformat: 4, nbformat_minor: 5 }) + fs.writeFileSync(file, body) + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const edit = makeEditImpl( + pathSvc, + makeNotebookFileService(), + makePermissionService(makeContext(dir)) + ) + const before = process.memoryUsage().rss + const started = Bun.nanoseconds() + await Effect.runPromise( + edit.editCell(file, { cellIndex: 5, source: "print(2)", clearOutputs: "always" }) + ) + return { + ms: (Bun.nanoseconds() - started) / 1e6, + rssDeltaMb: (process.memoryUsage().rss - before) / 1e6, + mb: body.length / 1e6 + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +const measurePatchAllocation = (): { ok: boolean; line: string } => { + const result = Bun.spawnSync( + [process.execPath, "--expose-gc", path.join(import.meta.dir, "bench-alloc.ts")], + { stdout: "pipe", stderr: "pipe" } + ) + const output = `${result.stdout.toString()}${result.stderr.toString()}`.trim() + return { ok: (result.exitCode ?? 1) === 0, line: output.split("\n").slice(-2).join(" | ") } +} + +const measureCompactPatchScaling = (): { ms: number; ratio: number } => { + const { patchJsonTextDetailed } = require("../src/utils/json-patch.js") as { + patchJsonTextDetailed: ( + text: string, + next: unknown, + options: { style: Record } + ) => { text?: string; reason?: string } + } + const style = { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + const run = (keys: number): number => { + const metadata: Record = {} + for (let index = 0; index < keys; index += 1) { + metadata[`k${String(index).padStart(7, "0")}`] = index + } + const text = JSON.stringify({ + cells: [], + metadata, + nbformat: 4, + nbformat_minor: 5 + }) + const next = JSON.parse(text) as { metadata: Record } + for (const key of Object.keys(next.metadata)) next.metadata[key] = -1 + const started = Bun.nanoseconds() + patchJsonTextDetailed(text, next, { style }) + return (Bun.nanoseconds() - started) / 1e6 + } + run(4_000) + const small = run(16_000) + const large = run(64_000) + return { ms: large, ratio: large / Math.max(small, 0.5) } +} + +const main = async (): Promise => { + await measure(SMALL) + const small = await measure(SMALL) + const large = await measure(LARGE) + const ratio = ratios(small, large) + for (const sample of [small, large]) { + console.log( + `cells=${sample.cells} bytes=${sample.bytes} clearAll=${sample.clearAllMs.toFixed(1)}ms move=${sample.moveMs.toFixed(1)}ms edit=${sample.editMs.toFixed(1)}ms patchAll=${sample.patchMs.toFixed(1)}ms` + ) + } + console.log( + `scaling ${SMALL}->${LARGE} cells (${ratio.cells.toFixed(1)}x input): clearAll=${ratio.clearAll.toFixed(1)}x move=${ratio.move.toFixed(1)}x edit=${ratio.edit.toFixed(1)}x patchAll=${ratio.patch.toFixed(1)}x` + ) + const normalized = { + clearAll: ratio.clearAll / ratio.bytes, + move: ratio.move / ratio.bytes, + edit: ratio.edit / ratio.bytes, + patch: ratio.patch / ratio.bytes + } + console.log( + `cost per byte vs linear: clearAll=${normalized.clearAll.toFixed(2)}x move=${normalized.move.toFixed(2)}x edit=${normalized.edit.toFixed(2)}x patchAll=${normalized.patch.toFixed(2)}x` + ) + const metadataSmall = medianMs( + Array.from({ length: 3 }, () => measureMetadataPatch(META_SMALL)) + ) + const metadataLarge = medianMs( + Array.from({ length: 3 }, () => measureMetadataPatch(META_LARGE)) + ) + const metadataRatio = + metadataLarge / Math.max(metadataSmall, 0.5) / (META_LARGE / META_SMALL) + console.log( + `metadata object patch ${META_SMALL}->${META_LARGE} keys: ${metadataSmall.toFixed(1)}ms -> ${metadataLarge.toFixed(1)}ms (${metadataRatio.toFixed(2)}x of linear)` + ) + const interleavedSmall = medianMs( + Array.from({ length: 3 }, () => measureInterleavedMetadataPatch(INTERLEAVED_SMALL)) + ) + const interleavedLarge = medianMs( + Array.from({ length: 3 }, () => measureInterleavedMetadataPatch(INTERLEAVED_LARGE)) + ) + const interleavedRatio = + interleavedLarge / + Math.max(interleavedSmall, 0.5) / + (INTERLEAVED_LARGE / INTERLEAVED_SMALL) + console.log( + `interleaved metadata patch ${INTERLEAVED_SMALL}->${INTERLEAVED_LARGE} keys: ${interleavedSmall.toFixed(1)}ms -> ${interleavedLarge.toFixed(1)}ms (${interleavedRatio.toFixed(2)}x of linear)` + ) + const largeOutput = measureLargeOutput() + console.log( + `large per-cell output 40MB with maxOutputChars=6000: ${largeOutput.ms.toFixed(1)}ms, rss +${largeOutput.rssDeltaMb.toFixed(0)}MB` + ) + const unicodeEscape = measureUnicodeEscape() + console.log( + `unicode escape 4MB ensureAscii: ${unicodeEscape.ms.toFixed(1)}ms, rss +${unicodeEscape.rssDeltaMb.toFixed(0)}MB` + ) + const compactScaling = measureCompactPatchScaling() + console.log( + `compact notebook patch 16k->64k keys: ${compactScaling.ms.toFixed(0)}ms (${compactScaling.ratio.toFixed(1)}x for 4x input)` + ) + const patchAllocation = measurePatchAllocation() + console.log(`patch allocation guard: ${patchAllocation.line}`) + const objectHeavy = measureObjectHeavyPatch() + console.log( + `one-key edit in 64k-key metadata: ${objectHeavy.ms.toFixed(0)}ms, rss +${objectHeavy.rssDeltaMb.toFixed(0)}MB` + ) + const largeEdit = await measureLargeNotebookEdit() + console.log( + `one-cell edit in a ${largeEdit.mb.toFixed(1)}MB / 64k-cell notebook: ${largeEdit.ms.toFixed(0)}ms, rss +${largeEdit.rssDeltaMb.toFixed(0)}MB` + ) + const failures: string[] = [] + if (compactScaling.ratio > 12) failures.push(`compactPatchRatio ${compactScaling.ratio.toFixed(1)}x`) + if (compactScaling.ms > 3_000) failures.push(`compactPatchTime ${compactScaling.ms.toFixed(0)}ms`) + if (!patchAllocation.ok) failures.push("patchAllocation (see bench-alloc.ts)") + // Absolute budget only, not an implementation discriminator: this machine + // measured 421-585 ms and a CI container 682-799 ms for the same code, so the + // box decides the number. Complexity is pinned by compactPatchRatio below, + // which fails the previous isMultiline at 12.8x; this ceiling only catches a + // runaway regression. + if (largeEdit.ms > 2_000) failures.push(`largeEditTime ${largeEdit.ms.toFixed(0)}ms`) + if (largeEdit.rssDeltaMb > 400) failures.push(`largeEditRss ${largeEdit.rssDeltaMb.toFixed(0)}MB`) + // The object-heavy delta is often negative (the GC frees more than the patch + // allocates), so only the time budget is meaningful here. + if (objectHeavy.ms > 400) failures.push(`objectHeavyTime ${objectHeavy.ms.toFixed(0)}ms`) + if (unicodeEscape.ms > 400) failures.push(`unicodeEscapeTime ${unicodeEscape.ms.toFixed(1)}ms`) + if (unicodeEscape.rssDeltaMb > 200) failures.push(`unicodeEscapeRss ${unicodeEscape.rssDeltaMb.toFixed(0)}MB`) + // 0.7-1.1 ms with the pre-truncation, 14.2 ms without it (20x), so a 5 ms + // ceiling separates them with room for this machine's variance. + if (largeOutput.ms > 5) failures.push(`largeOutputTime ${largeOutput.ms.toFixed(1)}ms`) + if (largeOutput.rssDeltaMb > 100) failures.push(`largeOutputRss ${largeOutput.rssDeltaMb.toFixed(0)}MB`) + if (normalized.clearAll > BUDGET) failures.push(`clearAll ${normalized.clearAll.toFixed(2)}x`) + if (normalized.move > BUDGET) failures.push(`move ${normalized.move.toFixed(2)}x`) + if (normalized.edit > BUDGET) failures.push(`edit ${normalized.edit.toFixed(2)}x`) + if (normalized.patch > BUDGET) failures.push(`patchAll ${normalized.patch.toFixed(2)}x`) + if (metadataRatio > BUDGET) failures.push(`metadataPatch ${metadataRatio.toFixed(2)}x`) + if (interleavedRatio > BUDGET) { + failures.push(`interleavedMetadataPatch ${interleavedRatio.toFixed(2)}x`) + } + if (failures.length > 0) { + console.error( + `FAIL: write cost grows faster than the notebook (budget ${BUDGET}x linear): ${failures.join(", ")}` + ) + process.exit(1) + } + console.log(`ok: every write is within ${BUDGET}x of linear for a ${ratio.bytes.toFixed(1)}x larger notebook`) +} + +await main() diff --git a/scripts/prepack-check.ts b/scripts/prepack-check.ts new file mode 100644 index 0000000..710ded2 --- /dev/null +++ b/scripts/prepack-check.ts @@ -0,0 +1,79 @@ +#!/usr/bin/env bun +import { execFileSync } from "node:child_process" +import * as fs from "node:fs" +import * as path from "node:path" + +interface PackFile { + readonly path: string +} + +const root = path.resolve(import.meta.dir, "..") + +const required = [ + "dist/index.js", + "dist/index.d.ts", + "dist/lsp.js", + "dist/lsp.d.ts", + "dist/rpc.js", + "dist/rpc.d.ts", + "server.js", + "python/ipynb_runner.py", + "python/requirements.txt", + "README.md", + "CHANGELOG.md", + "LICENSE" +] + +const staleMarkers = [ + "the existing notebook could not be read; refusing to overwrite it", + "another process replaced the notebook right after the write", + "nothing was changed" +] + +const failures: string[] = [] + +for (const entry of required) { + if (!fs.existsSync(path.join(root, entry))) { + failures.push(`${entry} is missing from the repository; run: bun run build`) + } +} + +let packed: string[] = [] +try { + const output = execFileSync("npm", ["pack", "--dry-run", "--json", "--ignore-scripts"], { + cwd: root, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"] + }) + const parsed = JSON.parse(output) as Array<{ files?: PackFile[] }> + packed = (parsed[0]?.files ?? []).map((file) => file.path) +} catch (error) { + failures.push( + `npm pack --dry-run failed: ${error instanceof Error ? error.message : String(error)}` + ) +} + +for (const entry of required) { + if (packed.length > 0 && !packed.includes(entry)) { + failures.push(`${entry} is not in the packed file set`) + } +} + +const bundle = path.join(root, "dist", "index.js") +if (fs.existsSync(bundle)) { + const text = fs.readFileSync(bundle, "utf8") + for (const marker of staleMarkers) { + if (!text.includes(marker)) { + failures.push( + `dist/index.js is stale: missing "${marker}" (run: bun run build)` + ) + } + } +} + +if (failures.length > 0) { + for (const failure of failures) console.error(`prepack: ${failure}`) + process.exit(1) +} + +console.log(`prepack: ${packed.length} packed files, required entries present, dist is current`) diff --git a/specs/.gitignore b/specs/.gitignore new file mode 100644 index 0000000..8c2dba1 --- /dev/null +++ b/specs/.gitignore @@ -0,0 +1,3 @@ +states/ +*.bin +*_TTrace_*.tla diff --git a/specs/KernelWarningRing.cfg b/specs/KernelWarningRing.cfg new file mode 100644 index 0000000..7bb9ec4 --- /dev/null +++ b/specs/KernelWarningRing.cfg @@ -0,0 +1,17 @@ +SPECIFICATION Spec + +CONSTANTS + Capacity = 3 + Messages = {"m1", "m2", "m3", "m4", "m5"} + ClearThreshold = 2 + +INVARIANT + TypeOK + NoDuplicatesWithinEpoch + DeliveredBounded + +PROPERTY + Bounded + +CONSTRAINT + StateConstraint diff --git a/specs/KernelWarningRing.tla b/specs/KernelWarningRing.tla new file mode 100644 index 0000000..314b607 --- /dev/null +++ b/specs/KernelWarningRing.tla @@ -0,0 +1,91 @@ +---------------- MODULE KernelWarningRing ---------------- +EXTENDS Naturals, Sequences, FiniteSets + +CONSTANTS Capacity, Messages, ClearThreshold + +VARIABLES seen, ring, ringEpochs, delivered, epochs + +Init == + /\ seen = {} + /\ ring = <<>> + /\ ringEpochs = <<>> + /\ delivered = 0 + /\ epochs = 0 + +\* Mirrors KernelManager.record: the dedup check comes first, then the +\* anti-leak clear when the set has reached its threshold, then the add. +\* The TS clears the dedup set in place, so a message recorded in an +\* earlier epoch can be delivered again; the epoch counters make that +\* behavior explicit instead of forbidding it. +Record(m) == + /\ m \in Messages + /\ m \notin seen + /\ Cardinality(seen) < ClearThreshold + /\ seen' = seen \union {m} + /\ ring' = IF Len(ring) >= Capacity + THEN Tail(ring) \o <> + ELSE Append(ring, m) + /\ ringEpochs' = IF Len(ringEpochs) >= Capacity + THEN Tail(ringEpochs) \o <> + ELSE Append(ringEpochs, epochs) + /\ delivered' = delivered + 1 + /\ UNCHANGED epochs + +RecordAfterClear(m) == + /\ m \in Messages + /\ m \notin seen + /\ Cardinality(seen) >= ClearThreshold + /\ seen' = {m} + /\ epochs' = epochs + 1 + /\ ring' = IF Len(ring) >= Capacity + THEN Tail(ring) \o <> + ELSE Append(ring, m) + /\ ringEpochs' = IF Len(ringEpochs) >= Capacity + THEN Tail(ringEpochs) \o <> + ELSE Append(ringEpochs, epochs') + /\ delivered' = delivered + 1 + +Duplicate(m) == + /\ m \in seen + /\ UNCHANGED <> + +Next == + \/ \E m \in Messages : Record(m) + \/ \E m \in Messages : RecordAfterClear(m) + \/ \E m \in Messages : Duplicate(m) + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ ring \in Seq(Messages) + /\ Len(ring) <= Capacity + /\ seen \subseteq Messages + /\ Cardinality(seen) <= ClearThreshold + /\ Len(ringEpochs) = Len(ring) + /\ \A i \in 1..Len(ringEpochs) : ringEpochs[i] \in Nat + /\ \A i \in 1..Len(ringEpochs) : ringEpochs[i] <= epochs + /\ delivered \in Nat + /\ epochs \in Nat + +StateConstraint == + epochs <= 2 + +Bounded == + [][Len(ring) <= Capacity]_ring + +\* Within one epoch the dedup set still holds, so the ring cannot hold +\* the same message twice; across epochs it can, and that is honest. +NoDuplicatesWithinEpoch == + \A i, j \in 1..Len(ring) : + (ring[i] = ring[j] /\ ringEpochs[i] = ringEpochs[j]) => i = j + +\* The delivered history is bounded by what is still deduplicated plus +\* one full threshold window per clear. +\* The anti-leak clear bounds how many messages survive between clears. This +\* invariant alone does NOT pin that the clear happens: if `seen` never clears, +\* it grows and the bound still holds. NoDuplicatesWithinEpoch is what pins the +\* ring's shape, and the twin demonstrates why both are needed. +DeliveredBounded == + delivered <= Cardinality(seen) + ClearThreshold * epochs + +===================================== diff --git a/specs/KernelWarningRingNoDedup.cfg b/specs/KernelWarningRingNoDedup.cfg new file mode 100644 index 0000000..6b8bb94 --- /dev/null +++ b/specs/KernelWarningRingNoDedup.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec + +CONSTANTS + Capacity = 3 + Messages = {"m1", "m2", "m3", "m4", "m5"} + ClearThreshold = 2 + +INVARIANT + TypeOK + NoDuplicatesWithinEpoch + +CONSTRAINT + StateConstraint diff --git a/specs/KernelWarningRingNoDedup.expect b/specs/KernelWarningRingNoDedup.expect new file mode 100644 index 0000000..ab4c772 --- /dev/null +++ b/specs/KernelWarningRingNoDedup.expect @@ -0,0 +1 @@ +Invariant NoDuplicatesWithinEpoch is violated diff --git a/specs/KernelWarningRingNoDedup.tla b/specs/KernelWarningRingNoDedup.tla new file mode 100644 index 0000000..08cfff5 --- /dev/null +++ b/specs/KernelWarningRingNoDedup.tla @@ -0,0 +1,68 @@ +---------------- MODULE KernelWarningRingNoDedup ---------------- +EXTENDS Naturals, Sequences, FiniteSets + +\* Dishonest twin of KernelWarningRing: `record` forgets the dedup check, +\* so the same message is delivered again inside one epoch and the ring can +\* hold it twice. NotebookWarningRing's NoDuplicatesWithinEpoch is the +\* property this twin violates. + +CONSTANTS Capacity, Messages, ClearThreshold + +VARIABLES seen, ring, ringEpochs, delivered, epochs + +Init == + /\ seen = {} + /\ ring = <<>> + /\ ringEpochs = <<>> + /\ delivered = 0 + /\ epochs = 0 + +Record(m) == + /\ m \in Messages + /\ Cardinality(seen) < ClearThreshold + /\ seen' = seen \union {m} + /\ ring' = IF Len(ring) >= Capacity + THEN Tail(ring) \o <> + ELSE Append(ring, m) + /\ ringEpochs' = IF Len(ringEpochs) >= Capacity + THEN Tail(ringEpochs) \o <> + ELSE Append(ringEpochs, epochs) + /\ delivered' = delivered + 1 + /\ UNCHANGED epochs + +RecordAfterClear(m) == + /\ m \in Messages + /\ Cardinality(seen) >= ClearThreshold + /\ seen' = {m} + /\ epochs' = epochs + 1 + /\ ring' = IF Len(ring) >= Capacity + THEN Tail(ring) \o <> + ELSE Append(ring, m) + /\ ringEpochs' = IF Len(ringEpochs) >= Capacity + THEN Tail(ringEpochs) \o <> + ELSE Append(ringEpochs, epochs') + /\ delivered' = delivered + 1 + +Next == + \/ \E m \in Messages : Record(m) + \/ \E m \in Messages : RecordAfterClear(m) + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ ring \in Seq(Messages) + /\ Len(ring) <= Capacity + /\ seen \subseteq Messages + /\ Cardinality(seen) <= ClearThreshold + /\ Len(ringEpochs) = Len(ring) + /\ delivered \in Nat + /\ epochs \in Nat + +StateConstraint == + epochs <= 2 + +NoDuplicatesWithinEpoch == + \A i, j \in 1..Len(ring) : + (ring[i] = ring[j] /\ ringEpochs[i] = ringEpochs[j]) => i = j + +===================================== diff --git a/specs/NotebookAtomicReplace.cfg b/specs/NotebookAtomicReplace.cfg new file mode 100644 index 0000000..c6fe286 --- /dev/null +++ b/specs/NotebookAtomicReplace.cfg @@ -0,0 +1,13 @@ +SPECIFICATION Spec + +INVARIANT + TypeOK + TargetNeverPartial + DoneSuccess + RaisedKeepsOriginal + NoSilentVanish + LeftoverBackupAnnounced + OrphanTempRaised + +CHECK_DEADLOCK + FALSE diff --git a/specs/NotebookAtomicReplace.tla b/specs/NotebookAtomicReplace.tla new file mode 100644 index 0000000..d9563d3 --- /dev/null +++ b/specs/NotebookAtomicReplace.tla @@ -0,0 +1,148 @@ +---------------- MODULE NotebookAtomicReplace ---------------- +\* Scope: this models ONLY the win32 branch of utils/atomic-replace.ts. On +\* POSIX the module returns after the first rename (or rethrows), so the +\* backup/restore/cleanup states below are unreachable there: the POSIX +\* protocol is the DirectOk / DirectFailRaise pair. A POSIX deployment of this +\* spec would be a much smaller model, not this one. +EXTENDS Naturals + +VARIABLES phase, target, backup, temp, raised, warned + +Init == + /\ phase = "start" + /\ target = "old" + /\ backup = "absent" + /\ temp = "new" + /\ raised = FALSE + /\ warned = FALSE + +DirectOk == + /\ phase = "start" + /\ phase' = "done" + /\ target' = "new" + /\ temp' = "absent" + /\ UNCHANGED <> + +DirectFailRaise == + /\ phase = "start" + /\ phase' = "done" + /\ raised' = TRUE + /\ UNCHANGED <> + +DirectFailRetry == + /\ phase = "start" + /\ phase' = "retrying" + /\ UNCHANGED <> + +BackupOk == + /\ phase = "retrying" + /\ phase' = "retry" + /\ backup' = "old" + /\ target' = "absent" + /\ UNCHANGED <> + +BackupFail == + /\ phase = "retrying" + /\ phase' = "retry" + /\ warned' = TRUE + /\ UNCHANGED <> + +MoveOk == + /\ phase = "retry" + /\ phase' = "moved" + /\ target' = "new" + /\ temp' = "absent" + /\ UNCHANGED <> + +MoveFailWithBackup == + /\ phase = "retry" + /\ backup = "old" + /\ phase' = "restoring" + /\ UNCHANGED <> + +MoveFailNoBackup == + /\ phase = "retry" + /\ backup = "absent" + /\ phase' = "done" + /\ raised' = TRUE + /\ UNCHANGED <> + +RestoreOk == + /\ phase = "restoring" + /\ phase' = "done" + /\ backup' = "absent" + /\ target' = "old" + /\ raised' = TRUE + /\ UNCHANGED <> + +RestoreFail == + /\ phase = "restoring" + /\ phase' = "done" + /\ raised' = TRUE + /\ warned' = TRUE + /\ UNCHANGED <> + +CleanupOk == + /\ phase = "moved" + /\ backup = "old" + /\ phase' = "done" + /\ backup' = "absent" + /\ UNCHANGED <> + +CleanupFail == + /\ phase = "moved" + /\ backup = "old" + /\ phase' = "done" + /\ warned' = TRUE + /\ UNCHANGED <> + +FinishNoBackup == + /\ phase = "moved" + /\ backup = "absent" + /\ phase' = "done" + /\ UNCHANGED <> + +Next == + \/ DirectOk + \/ DirectFailRaise + \/ DirectFailRetry + \/ BackupOk + \/ BackupFail + \/ MoveOk + \/ MoveFailWithBackup + \/ MoveFailNoBackup + \/ RestoreOk + \/ RestoreFail + \/ CleanupOk + \/ CleanupFail + \/ FinishNoBackup + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ phase \in {"start", "retrying", "retry", "moved", "restoring", "done"} + /\ target \in {"old", "new", "absent"} + /\ backup \in {"old", "absent"} + /\ temp \in {"new", "absent"} + /\ raised \in BOOLEAN + /\ warned \in BOOLEAN + +TargetNeverPartial == + target \in {"old", "new", "absent"} + +DoneSuccess == + phase = "done" => (raised = FALSE => target = "new") + +RaisedKeepsOriginal == + phase = "done" /\ raised => target = "old" \/ backup = "old" + +NoSilentVanish == + phase = "done" /\ target = "absent" => raised + +LeftoverBackupAnnounced == + phase = "done" /\ backup = "old" => warned + +OrphanTempRaised == + phase = "done" /\ temp = "new" => raised + +============================================================================= diff --git a/specs/NotebookAtomicReplaceInPlace.cfg b/specs/NotebookAtomicReplaceInPlace.cfg new file mode 100644 index 0000000..7f4bbce --- /dev/null +++ b/specs/NotebookAtomicReplaceInPlace.cfg @@ -0,0 +1,8 @@ +SPECIFICATION Spec + +INVARIANT + TypeOK + TargetNeverPartial + +CHECK_DEADLOCK + FALSE diff --git a/specs/NotebookAtomicReplaceInPlace.expect b/specs/NotebookAtomicReplaceInPlace.expect new file mode 100644 index 0000000..b156e25 --- /dev/null +++ b/specs/NotebookAtomicReplaceInPlace.expect @@ -0,0 +1 @@ +Invariant TargetNeverPartial is violated diff --git a/specs/NotebookAtomicReplaceInPlace.tla b/specs/NotebookAtomicReplaceInPlace.tla new file mode 100644 index 0000000..fd742eb --- /dev/null +++ b/specs/NotebookAtomicReplaceInPlace.tla @@ -0,0 +1,35 @@ +---------------- MODULE NotebookAtomicReplaceInPlace ---------------- +EXTENDS Naturals + +VARIABLES phase, target + +Init == + /\ phase = "writing" + /\ target = "old" + +BeginInPlace == + /\ phase = "writing" + /\ target = "old" + /\ target' = "partial" + /\ UNCHANGED phase + +FinishInPlace == + /\ phase = "writing" + /\ target = "partial" + /\ phase' = "done" + /\ target' = "new" + +Next == + \/ BeginInPlace + \/ FinishInPlace + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ phase \in {"writing", "done"} + /\ target \in {"old", "partial", "new"} + +TargetNeverPartial == + target # "partial" + +============================================================================= diff --git a/specs/NotebookExecutionSave.cfg b/specs/NotebookExecutionSave.cfg new file mode 100644 index 0000000..19a7e75 --- /dev/null +++ b/specs/NotebookExecutionSave.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec + +INVARIANT + TypeOK + SavedVersionMatches + +CONSTRAINT + StateConstraint + +CHECK_DEADLOCK + FALSE diff --git a/specs/NotebookExecutionSave.tla b/specs/NotebookExecutionSave.tla new file mode 100644 index 0000000..389b770 --- /dev/null +++ b/specs/NotebookExecutionSave.tla @@ -0,0 +1,67 @@ +---------------- MODULE NotebookExecutionSave ---------------- +EXTENDS Naturals + +\* SaveChecked collapses the under-lock re-read, the hash comparison, +\* and the atomic rename into a single step. That check-to-rename +\* atomicity is this model's stated assumption: the plugin-internal +\* file lock serializes plugin writers, but a non-cooperating external +\* writer keeps a residual window after the final read that no +\* in-process protocol can close. ExternalWrite stays enabled after a +\* save for the same reason. + +VARIABLES stage, snapshot, disk, savedVersion + +Init == + /\ stage = "idle" + /\ snapshot = 0 + /\ disk = 0 + /\ savedVersion = 0 + +ReadSnapshot == + /\ stage = "idle" + /\ snapshot' = disk + /\ stage' = "executing" + /\ UNCHANGED <> + +ExternalWrite == + /\ disk' = disk + 1 + /\ UNCHANGED <> + +SaveChecked == + /\ stage = "executing" + /\ disk = snapshot + /\ disk' = disk + 1 + /\ savedVersion' = disk' + /\ stage' = "saved" + /\ UNCHANGED snapshot + +SaveAborted == + /\ stage = "executing" + /\ disk /= snapshot + /\ stage' = "aborted" + /\ UNCHANGED <> + +Next == + \/ ReadSnapshot + \/ ExternalWrite + \/ SaveChecked + \/ SaveAborted + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ stage \in {"idle", "executing", "saved", "aborted"} + /\ snapshot \in Nat + /\ disk \in Nat + /\ savedVersion \in Nat + +StateConstraint == + disk <= 3 + +\* A completed save wrote exactly the snapshotted version plus the save +\* itself; the recheck guard is what keeps this true, and the +\* NotebookExecutionSaveNoRecheck twin violates it. +SavedVersionMatches == + stage = "saved" => savedVersion = snapshot + 1 + +===================================== diff --git a/specs/NotebookExecutionSaveNoRecheck.cfg b/specs/NotebookExecutionSaveNoRecheck.cfg new file mode 100644 index 0000000..19a7e75 --- /dev/null +++ b/specs/NotebookExecutionSaveNoRecheck.cfg @@ -0,0 +1,11 @@ +SPECIFICATION Spec + +INVARIANT + TypeOK + SavedVersionMatches + +CONSTRAINT + StateConstraint + +CHECK_DEADLOCK + FALSE diff --git a/specs/NotebookExecutionSaveNoRecheck.expect b/specs/NotebookExecutionSaveNoRecheck.expect new file mode 100644 index 0000000..f9636b4 --- /dev/null +++ b/specs/NotebookExecutionSaveNoRecheck.expect @@ -0,0 +1 @@ +Invariant SavedVersionMatches is violated diff --git a/specs/NotebookExecutionSaveNoRecheck.tla b/specs/NotebookExecutionSaveNoRecheck.tla new file mode 100644 index 0000000..8a4fe7a --- /dev/null +++ b/specs/NotebookExecutionSaveNoRecheck.tla @@ -0,0 +1,51 @@ +---------------- MODULE NotebookExecutionSaveNoRecheck ---------------- +EXTENDS Naturals + +\* The dishonest twin of NotebookExecutionSave: the save skips the +\* under-lock recheck and lands whatever version it likes. + +VARIABLES stage, snapshot, disk, savedVersion + +Init == + /\ stage = "idle" + /\ snapshot = 0 + /\ disk = 0 + /\ savedVersion = 0 + +ReadSnapshot == + /\ stage = "idle" + /\ snapshot' = disk + /\ stage' = "executing" + /\ UNCHANGED <> + +ExternalWrite == + /\ disk' = disk + 1 + /\ UNCHANGED <> + +SaveWithoutRecheck == + /\ stage = "executing" + /\ disk' = disk + 1 + /\ savedVersion' = disk' + /\ stage' = "saved" + /\ UNCHANGED snapshot + +Next == + \/ ReadSnapshot + \/ ExternalWrite + \/ SaveWithoutRecheck + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ stage \in {"idle", "executing", "saved"} + /\ snapshot \in Nat + /\ disk \in Nat + /\ savedVersion \in Nat + +StateConstraint == + disk <= 3 + +SavedVersionMatches == + stage = "saved" => savedVersion = snapshot + 1 + +===================================== diff --git a/specs/NotebookWriteLock.cfg b/specs/NotebookWriteLock.cfg new file mode 100644 index 0000000..9a4f62d --- /dev/null +++ b/specs/NotebookWriteLock.cfg @@ -0,0 +1,17 @@ +SPECIFICATION Spec + +CONSTANTS + Writers = {"w1", "w2"} + None = "none" + +INVARIANT + TypeOK + MutualExclusion + HolderMatchesHeld + NoLostUpdate + +CONSTRAINT + StateConstraint + +CHECK_DEADLOCK + FALSE diff --git a/specs/NotebookWriteLock.tla b/specs/NotebookWriteLock.tla new file mode 100644 index 0000000..c2cb06d --- /dev/null +++ b/specs/NotebookWriteLock.tla @@ -0,0 +1,97 @@ +---------------- MODULE NotebookWriteLock ---------------- +EXTENDS Naturals, FiniteSets + +CONSTANTS Writers, None + +\* ExternalWrite stays enabled even while a writer holds the lock: the +\* file lock is an in-process semaphore and an external writer such as +\* Jupyter never takes it. WriteChecked collapses the recheck, the +\* write, and the rename into one step, so the check-to-rename window +\* against a non-cooperating external writer is the same stated +\* assumption as in NotebookExecutionSave. AbortChecked is the honest +\* exit when the recheck sees an update that landed mid-window. + +VARIABLES holder, held, disk, revision, running, finished, wrote, stale + +Init == + /\ holder = None + /\ held = {} + /\ disk = 0 + /\ revision = 0 + /\ running = Writers + /\ finished = {} + /\ wrote = {} + /\ stale = [w \in Writers |-> FALSE] + +Acquire(w) == + /\ w \in running + /\ holder = None + /\ holder' = w + /\ held' = held \union {w} + /\ revision' = disk + /\ stale' = [stale EXCEPT ![w] = FALSE] + /\ UNCHANGED <> + +WriteChecked(w) == + /\ holder = w + /\ disk = revision + /\ disk' = disk + 1 + /\ holder' = None + /\ running' = running \ {w} + /\ finished' = finished \union {w} + /\ wrote' = wrote \union {w} + /\ held' = held \ {w} + /\ UNCHANGED <> + +AbortChecked(w) == + /\ holder = w + /\ disk /= revision + /\ holder' = None + /\ running' = running \ {w} + /\ finished' = finished \union {w} + /\ held' = held \ {w} + /\ UNCHANGED <> + +ExternalWrite == + /\ disk' = disk + 1 + /\ stale' = IF holder = None + THEN stale + ELSE [stale EXCEPT ![holder] = TRUE] + /\ UNCHANGED <> + +Next == + \/ \E w \in running : Acquire(w) + \/ \E w \in running : WriteChecked(w) + \/ \E w \in running : AbortChecked(w) + \/ ExternalWrite + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ holder \in (Writers \union {None}) + /\ running \subseteq Writers + /\ finished \subseteq Writers + /\ wrote \subseteq finished + /\ running \intersect finished = {} + /\ held \subseteq Writers + /\ disk \in Nat + /\ revision \in Nat + /\ stale \in [Writers -> BOOLEAN] + +StateConstraint == + /\ disk <= 3 + /\ revision <= 3 + +MutualExclusion == + Cardinality(held) <= 1 + +HolderMatchesHeld == + holder = None <=> held = {} + +\* Every completed write saw the same disk version at its check as at +\* its acquire, so no external update was clobbered on the way. The +\* NotebookWriteLockLostUpdate twin violates this. +NoLostUpdate == + \A w \in wrote : stale[w] = FALSE + +===================================== diff --git a/specs/NotebookWriteLockLostUpdate.cfg b/specs/NotebookWriteLockLostUpdate.cfg new file mode 100644 index 0000000..2fdc3e3 --- /dev/null +++ b/specs/NotebookWriteLockLostUpdate.cfg @@ -0,0 +1,12 @@ +SPECIFICATION Spec + +CONSTANTS + Writers = {"w1"} + None = "none" + +INVARIANT + TypeOK + NoLostUpdate + +CONSTRAINT + StateConstraint diff --git a/specs/NotebookWriteLockLostUpdate.expect b/specs/NotebookWriteLockLostUpdate.expect new file mode 100644 index 0000000..2469e32 --- /dev/null +++ b/specs/NotebookWriteLockLostUpdate.expect @@ -0,0 +1 @@ +Invariant NoLostUpdate is violated \ No newline at end of file diff --git a/specs/NotebookWriteLockLostUpdate.tla b/specs/NotebookWriteLockLostUpdate.tla new file mode 100644 index 0000000..df3235b --- /dev/null +++ b/specs/NotebookWriteLockLostUpdate.tla @@ -0,0 +1,68 @@ +---------------- MODULE NotebookWriteLockLostUpdate ---------------- +EXTENDS Naturals + +\* The dishonest twin of NotebookWriteLock: the writer releases and +\* writes without rechecking the version it captured at acquire. + +CONSTANTS Writers, None + +VARIABLES holder, disk, revision, running, finished, wrote, stale + +Init == + /\ holder = None + /\ disk = 0 + /\ revision = 0 + /\ running = Writers + /\ finished = {} + /\ wrote = {} + /\ stale = [w \in Writers |-> FALSE] + +Acquire(w) == + /\ w \in running + /\ holder = None + /\ holder' = w + /\ revision' = disk + /\ stale' = [stale EXCEPT ![w] = FALSE] + /\ UNCHANGED <> + +WriteWithoutRecheck(w) == + /\ holder = w + /\ disk' = disk + 1 + /\ holder' = None + /\ running' = running \ {w} + /\ finished' = finished \union {w} + /\ wrote' = wrote \union {w} + /\ UNCHANGED <> + +ExternalWrite == + /\ disk' = disk + 1 + /\ stale' = IF holder = None + THEN stale + ELSE [stale EXCEPT ![holder] = TRUE] + /\ UNCHANGED <> + +Next == + \/ \E w \in running : Acquire(w) + \/ \E w \in running : WriteWithoutRecheck(w) + \/ ExternalWrite + +Spec == Init /\ [][Next]_<> + +TypeOK == + /\ holder \in (Writers \union {None}) + /\ running \subseteq Writers + /\ finished \subseteq Writers + /\ wrote \subseteq finished + /\ running \intersect finished = {} + /\ disk \in Nat + /\ revision \in Nat + /\ stale \in [Writers -> BOOLEAN] + +StateConstraint == + /\ disk <= 3 + /\ revision <= 3 + +NoLostUpdate == + \A w \in wrote : stale[w] = FALSE + +===================================== diff --git a/src/domain/cell.ts b/src/domain/cell.ts index bd0ca71..aeba6da 100644 --- a/src/domain/cell.ts +++ b/src/domain/cell.ts @@ -11,7 +11,7 @@ export const CodeCellSchema = z cell_type: z.literal("code"), id: z.string().optional(), metadata: CellMetadataSchema, - execution_count: z.union([z.number().int().nullable(), z.null()]), + execution_count: z.union([z.number().int(), z.null()]).default(null), source: SourceSchema, outputs: z.array(z.record(z.string(), z.unknown())).default([]) }) diff --git a/src/domain/notebook.ts b/src/domain/notebook.ts index 0dc6cd1..2f3595c 100644 --- a/src/domain/notebook.ts +++ b/src/domain/notebook.ts @@ -31,7 +31,7 @@ export type NotebookMetadataRaw = z.infer export const NotebookSchema = z .object({ nbformat: z.number().int(), - nbformat_minor: z.number().int().optional(), + nbformat_minor: z.number().int(), metadata: NotebookMetadataSchema.default({}), cells: z.array(CellSchema) }) @@ -46,3 +46,98 @@ export const normalizeSource = (source: z.infer): string => } export const cellSource = (cell: CellRaw): string => normalizeSource(cell.source) + +const LINE_BREAK = /\r\n|[\n\v\f\r\x1c\x1d\x1e\x85\u2028\u2029]/g + +export const splitSourceLines = (source: string): string[] => { + const lines: string[] = [] + let start = 0 + LINE_BREAK.lastIndex = 0 + for (let match = LINE_BREAK.exec(source); match !== null; match = LINE_BREAK.exec(source)) { + const end = match.index + match[0].length + lines.push(source.slice(start, end)) + start = end + } + if (start < source.length) lines.push(source.slice(start)) + return lines +} + +export const formatSourceLike = ( + previous: z.infer, + next: string +): z.infer => + typeof previous === "string" ? next : splitSourceLines(next) + +const defineOwn = ( + target: Record, + key: string, + value: unknown +): void => { + Object.defineProperty(target, key, { + value, + writable: true, + enumerable: true, + configurable: true + }) +} + +const isSorted = (keys: ReadonlyArray): boolean => { + for (let index = 1; index < keys.length; index += 1) { + if (keys[index - 1]! >= keys[index]!) return false + } + return true +} + +const insertSorted = ( + target: Record, + key: string, + value: unknown +): void => { + if (Object.prototype.hasOwnProperty.call(target, key)) return + const keys = Object.keys(target) + if (keys.length === 0 || !isSorted(keys)) { + defineOwn(target, key, value) + return + } + const index = keys.findIndex((candidate) => candidate > key) + if (index === -1) { + defineOwn(target, key, value) + return + } + defineOwn(target, key, value) + const inserted = Object.entries(target) + for (const [existing] of inserted) delete target[existing] + const moved = inserted.splice(inserted.length - 1, 1)[0]! + inserted.splice(index, 0, moved) + for (const [existing, existingValue] of inserted) { + defineOwn(target, existing, existingValue) + } +} + +export const applyNotebookDefaults = (raw: unknown): NotebookRaw => { + const nb = raw as { + metadata?: unknown + cells: Array> + } + let top = nb as Record + if (nb.metadata === undefined) { + top = { ...nb } + insertSorted(top, "metadata", {}) + } + let cells: Array> | undefined + for (let index = 0; index < nb.cells.length; index += 1) { + const cell = nb.cells[index]! + if (cell["cell_type"] !== "code" || cell["outputs"] !== undefined) { + if (cells !== undefined) cells.push(cell) + continue + } + if (cells === undefined) cells = nb.cells.slice(0, index) + const clone: Record = { ...cell } + insertSorted(clone, "outputs", []) + cells.push(clone) + } + if (cells === undefined) return top as NotebookRaw + if (top === (nb as Record)) top = { ...nb } + top["cells"] = cells + return top as NotebookRaw +} diff --git a/src/format/notebook.ts b/src/format/notebook.ts index 7298b03..da86a20 100644 --- a/src/format/notebook.ts +++ b/src/format/notebook.ts @@ -3,7 +3,6 @@ import { codeFence } from "../utils/fence.js" export interface MarkdownCellInput { readonly cell_type: "code" | "markdown" | "raw" readonly source: string - /** Rendered image links appended after a raw-cell fence. */ readonly attachments?: ReadonlyArray | undefined } diff --git a/src/format/outputs.ts b/src/format/outputs.ts index 845d981..92530f4 100644 --- a/src/format/outputs.ts +++ b/src/format/outputs.ts @@ -17,7 +17,6 @@ import type { ToolAttachment } from "../tool.js" export interface OutputFormatOptions { readonly includeImages: boolean - /** Use the hard-limit hint when the response cap, not the user, wins. */ readonly hardCap?: boolean | undefined readonly saveImages?: boolean | undefined readonly maxOutputChars: number @@ -42,8 +41,53 @@ const imageNotice = (mime: string, value: string): string => { return `${sanitizeInline(mime)}, ${humanBytes(bytes)}, omitted by default` } +const boundedForSanitize = (text: string, max: number): string => + text.length <= max * 2 + 256 ? text : text.slice(0, max * 2 + 256) + +const boundJsonValue = ( + value: unknown, + budget: number, + depth = 0 +): unknown => { + if (budget <= 0 || depth > 8) return "…" + if (typeof value === "string") { + return value.length <= budget ? value : `${value.slice(0, budget)}…` + } + if (Array.isArray(value)) { + const out: unknown[] = [] + let left = budget + for (const item of value) { + if (left <= 0) { + out.push(`… (${value.length - out.length} more items)`) + break + } + const bounded = boundJsonValue(item, Math.max(1, left), depth + 1) + out.push(bounded) + left -= JSON.stringify(bounded).length + } + return out + } + if (value !== null && typeof value === "object") { + const record = value as Record + const keys = Object.keys(record) + const out: Record = {} + let left = budget + for (const key of keys) { + if (left <= 0) { + out["…"] = `${keys.length - Object.keys(out).length} more keys` + break + } + const bounded = boundJsonValue(record[key], Math.max(1, left), depth + 1) + out[key] = bounded + left -= JSON.stringify(bounded).length + key.length + } + return out + } + return value +} + const formatStream = (text: string, max: number): string => { - const t = truncate(sanitizeTerminal(text), max, { + const t = truncate(sanitizeTerminal(boundedForSanitize(text, max)), max, { key: "stream", paramName: "maxOutputChars" }) @@ -83,17 +127,27 @@ const formatDisplay = ( lines.push(`- ${sanitizeInline(mime)}: (unsupported value type)`) } } else if (typeof value === "string") { - const t = truncate(sanitizeTerminal(value), opts.maxOutputChars, { - key: "output", - paramName: "maxOutputChars" - }) + const t = truncate( + sanitizeTerminal(boundedForSanitize(value, opts.maxOutputChars)), + opts.maxOutputChars, + { + key: "output", + paramName: "maxOutputChars" + } + ) lines.push(`- ${sanitizeInline(mime)}:`) const fence = codeFence(t.text) lines.push(fence) lines.push(t.text) lines.push(fence) } else { - const t = truncate(JSON.stringify(value, null, 2), opts.maxOutputChars, { key: "json", paramName: "maxOutputChars" }) + // Serializing a huge object only to slice it is quadratic work for a + // capped result: bound the structure first, then pretty-print it. + const t = truncate( + JSON.stringify(boundJsonValue(value, Math.max(1, opts.maxOutputChars * 2)), null, 2), + opts.maxOutputChars, + { key: "json", paramName: "maxOutputChars" } + ) const fence = codeFence(t.text) lines.push(`- ${sanitizeInline(mime)}:`) lines.push(`${fence}json`) @@ -135,17 +189,27 @@ const formatDisplayWithAttachments = async ( lines.push(`- ${sanitizeInline(mime)}: (unsupported value type)`) } } else if (typeof value === "string") { - const t = truncate(sanitizeTerminal(value), opts.maxOutputChars, { - key: "output", - paramName: "maxOutputChars" - }) + const t = truncate( + sanitizeTerminal(boundedForSanitize(value, opts.maxOutputChars)), + opts.maxOutputChars, + { + key: "output", + paramName: "maxOutputChars" + } + ) lines.push(`- ${sanitizeInline(mime)}:`) const fence = codeFence(t.text) lines.push(fence) lines.push(t.text) lines.push(fence) } else { - const t = truncate(JSON.stringify(value, null, 2), opts.maxOutputChars, { key: "json", paramName: "maxOutputChars" }) + // Serializing a huge object only to slice it is quadratic work for a + // capped result: bound the structure first, then pretty-print it. + const t = truncate( + JSON.stringify(boundJsonValue(value, Math.max(1, opts.maxOutputChars * 2)), null, 2), + opts.maxOutputChars, + { key: "json", paramName: "maxOutputChars" } + ) const fence = codeFence(t.text) lines.push(`- ${sanitizeInline(mime)}:`) lines.push(`${fence}json`) @@ -196,8 +260,8 @@ export const formatOutputs = ( return "" } const sections: string[] = [] - let stdout = "" - let stderr = "" + const stdoutParts: string[] = [] + const stderrParts: string[] = [] const displaySections: string[] = [] const resultSections: string[] = [] const errorSections: string[] = [] @@ -208,9 +272,9 @@ export const formatOutputs = ( const name = String(out["name"] ?? "") const text = outputTextToString(out["text"]) if (name === "stderr") { - stderr += text + stderrParts.push(text) } else { - stdout += text + stdoutParts.push(text) } } else if (kind === "display_data") { const data = (out["data"] as Record | undefined) ?? {} @@ -228,6 +292,9 @@ export const formatOutputs = ( } } + const stdout = stdoutParts.join("") + const stderr = stderrParts.join("") + if (stdout) { sections.push(`- **stdout**:\n${formatStream(stdout, opts.maxOutputChars)}`) } @@ -268,8 +335,8 @@ export const formatOutputsDetailed = async ( return { rendered: "", attachments: [] } } const sections: string[] = [] - let stdout = "" - let stderr = "" + const stdoutParts: string[] = [] + const stderrParts: string[] = [] const displaySections: string[] = [] const resultSections: string[] = [] const errorSections: string[] = [] @@ -281,9 +348,9 @@ export const formatOutputsDetailed = async ( const name = String(out["name"] ?? "") const text = outputTextToString(out["text"]) if (name === "stderr") { - stderr += text + stderrParts.push(text) } else { - stdout += text + stdoutParts.push(text) } } else if (kind === "display_data") { const data = (out["data"] as Record | undefined) ?? {} @@ -301,6 +368,9 @@ export const formatOutputsDetailed = async ( } } + const stdout = stdoutParts.join("") + const stderr = stderrParts.join("") + if (stdout) { sections.push(`- **stdout**:\n${formatStream(stdout, opts.maxOutputChars)}`) } diff --git a/src/load-document.ts b/src/load-document.ts index bc3bd85..2cf0fe6 100644 --- a/src/load-document.ts +++ b/src/load-document.ts @@ -10,15 +10,9 @@ export interface LoadDocumentContext { readonly worktree: string readonly allowOutsideWorktree?: boolean readonly options: PluginOptions - /** Materialization/RPC do not need a Python interpreter. */ readonly resolvePython?: boolean } -/** - * Resolve, confine, read, and project a notebook onto its virtual Python - * document. Shared by the RPC hook and ipynb_lsp so both use exactly the same - * real-path and option rules. - */ export const loadNotebookDocument = async ( context: LoadDocumentContext, filePath: string @@ -44,8 +38,6 @@ export const loadNotebookDocument = async ( try { pythonPath = resolvePythonPath(context.options) } catch { - // Materialization/RPC/automatic diagnostics must keep working when the - // configured interpreter is missing; include it only when resolvable. pythonPath = undefined } } diff --git a/src/lsp.ts b/src/lsp.ts index f2d4cd2..3606600 100644 --- a/src/lsp.ts +++ b/src/lsp.ts @@ -1,10 +1,3 @@ -/** - * Minimal notebook shape accepted by the virtual-document builder. - * - * It is structurally compatible with the plugin's parsed `NotebookRaw`, but - * keeping it local means the `opencode-ipynb/lsp` entry has no zod/Effect - * dependency and stays lightweight for third-party LSP plugins. - */ export interface NotebookLike { readonly metadata: { readonly language_info?: unknown @@ -16,44 +9,23 @@ export interface NotebookLike { }> } -/** - * A code cell projected into the notebook's virtual document. - * - * Line numbers are zero-based, matching LSP positions. `startLine` is the - * first virtual line for the cell and `endLine` is exclusive. - */ export interface NotebookCellDocument { readonly cellIndex: number readonly cellType: "code" | "markdown" | "raw" - /** LSP language id for this cell (`python`, `markdown`, `plaintext`). */ readonly languageId: string - /** Cell source, useful for native LSP 3.17 notebook sync. */ readonly text: string - /** Stable cell document URI when the caller provides one. */ readonly uri?: string readonly startLine: number readonly endLine: number readonly lineCount: number } -/** - * A single virtual document containing the notebook's code cells. - * - * Language servers do not understand `.ipynb` JSON, so tools can send `text` - * as a normal document and use `cells` to map positions back to the notebook. - * This is intentionally provider-agnostic: pyright, jedi-language-server, or a - * future OpenCode notebook LSP can all consume it. - */ export interface NotebookVirtualDocument { readonly filePath: string - /** Notebook URI (for clients that model notebook documents explicitly). */ readonly notebookUri?: string readonly languageId: string - /** Native language file extension from kernel metadata, e.g. `.py`. */ readonly fileExtension?: string - /** Jupyter kernelspec name, when present, so an LSP can select the right env. */ readonly kernelName?: string - /** Configured Python interpreter, when the plugin has one. */ readonly pythonPath?: string readonly text: string readonly cells: ReadonlyArray @@ -72,13 +44,9 @@ export interface VirtualPosition { export interface VirtualDocumentOptions { readonly filePath?: string - /** Include markdown/raw cells in the concatenated text. Defaults to false. */ readonly includeMarkdown?: boolean - /** Python interpreter configured for this plugin instance. */ readonly pythonPath?: string - /** URI representing the notebook itself. */ readonly notebookUri?: string - /** Stable URI for a cell document (native LSP 3.17 notebook sync). */ readonly cellUri?: (cellIndex: number) => string } @@ -180,14 +148,6 @@ const languageIdForCell = ( return notebookLanguage } -/** - * Build a virtual document from a parsed notebook. - * - * Code cells are separated by a newline, which preserves the cell-local line - * count and lets `toCellPosition`/`toVirtualPosition` map both directions. - * Each cell also carries its own text and optional URI so a client that - * supports LSP 3.17 notebook synchronization can use cell documents directly. - */ export const buildNotebookVirtualDocument = ( notebook: NotebookLike, options: VirtualDocumentOptions = {} @@ -232,15 +192,68 @@ export const buildNotebookVirtualDocument = ( } } -/** Map a zero-based position in the virtual document back to a cell position. */ +const cellCoveringLine = ( + cells: ReadonlyArray, + line: number +): NotebookCellDocument | undefined => { + let low = 0 + let high = cells.length - 1 + let candidate: NotebookCellDocument | undefined + while (low <= high) { + const mid = (low + high) >> 1 + const cell = cells[mid]! + if (cell.startLine <= line) { + candidate = cell + low = mid + 1 + } else { + high = mid - 1 + } + } + return candidate !== undefined && line < candidate.endLine ? candidate : undefined +} + +const cellPositionOfIndex = ( + cells: ReadonlyArray, + cellIndex: number +): number => { + let low = 0 + let high = cells.length - 1 + while (low <= high) { + const mid = (low + high) >> 1 + const cell = cells[mid]! + if (cell.cellIndex === cellIndex) return mid + if (cell.cellIndex < cellIndex) { + low = mid + 1 + } else { + high = mid - 1 + } + } + return -1 +} + +export const cellsAroundIndex = ( + document: NotebookVirtualDocument, + cellIndex: number +): + | { + readonly current: NotebookCellDocument + readonly previous: NotebookCellDocument | undefined + } + | undefined => { + const position = cellPositionOfIndex(document.cells, cellIndex) + if (position < 0) return undefined + return { + current: document.cells[position]!, + previous: position > 0 ? document.cells[position - 1] : undefined + } +} + export const toCellPosition = ( document: NotebookVirtualDocument, line: number, character: number ): CellPosition | undefined => { - const cell = document.cells.find( - (candidate) => line >= candidate.startLine && line < candidate.endLine - ) + const cell = cellCoveringLine(document.cells, line) if (!cell) return undefined return { cellIndex: cell.cellIndex, @@ -249,19 +262,18 @@ export const toCellPosition = ( } } -/** Map a zero-based position inside a cell to the virtual document. */ export const toVirtualPosition = ( document: NotebookVirtualDocument, cellIndex: number, line: number, character: number ): VirtualPosition | undefined => { - const cell = document.cells.find((candidate) => candidate.cellIndex === cellIndex) + const position = cellPositionOfIndex(document.cells, cellIndex) + const cell = position >= 0 ? document.cells[position] : undefined if (!cell || line < 0 || line >= cell.lineCount) return undefined return { line: cell.startLine + line, character } } -/** Convenience mapper bound to a built document. */ export const makePositionMapper = ( document: NotebookVirtualDocument ): PositionMapper => ({ diff --git a/src/notebook-diagnostics.ts b/src/notebook-diagnostics.ts index 70cf86e..934c413 100644 --- a/src/notebook-diagnostics.ts +++ b/src/notebook-diagnostics.ts @@ -9,10 +9,12 @@ import * as fs from "node:fs" import { promises as fsp } from "node:fs" import * as path from "node:path" import { + cellsAroundIndex, toCellPosition, type NotebookVirtualDocument } from "./lsp.js" import { PermissionDeniedError } from "./domain/errors.js" +import { type Warning, type WarningSink, warningFrom } from "./utils/warnings.js" const MAX_ERRORS = 20 @@ -25,29 +27,30 @@ export interface NotebookDiagnostic { readonly severity: "error" readonly message: string readonly rule?: string + /** pyright reported this for the whole file and supplied no position. */ + readonly fileLevel?: boolean } export interface NotebookDiagnosticsOptions { readonly filePath: string readonly document: NotebookVirtualDocument readonly displayPath?: string - /** Heading used in the report; defaults to displayPath. */ readonly where?: string readonly tempFilePath?: string - /** True when the plugin owns the temp file and may reuse/truncate it. */ readonly ownedTempFile?: boolean - /** Ask the host for permission before writing the system-temp fallback. */ readonly requestFallbackPermission?: () => Promise readonly pythonPath?: string readonly pyrightPath?: string readonly timeoutMs?: number readonly signal?: AbortSignal + readonly warningSink?: WarningSink } export interface NotebookDiagnosticsResult { readonly filePath: string readonly diagnostics: ReadonlyArray readonly text: string + readonly warnings?: ReadonlyArray readonly skipped?: | "pyright-not-found" | "timeout" @@ -56,11 +59,52 @@ export interface NotebookDiagnosticsResult { | "not-analyzed" | "temp-unwritable" | "pyright-not-executable" + | "unsafe-shell-command" } -/** Marker for temp-file failures so they are not confused with pyright spawn. */ class TempFileError extends Error {} +export class ShellCommandError extends Error {} + +export const hasShellMetacharacters = (value: string): boolean => + /["%&|<>^\r\n]/.test(value) + +export const shellCommandRefusal = ( + command: string, + args: ReadonlyArray, + shell: boolean +): ShellCommandError | undefined => { + if (!shell) return undefined + if (hasShellMetacharacters(command)) { + return new ShellCommandError( + `the pyright command ${JSON.stringify(command)} contains shell metacharacters` + ) + } + const index = args.findIndex(hasShellMetacharacters) + if (index >= 0) { + return new ShellCommandError( + `pyright argument ${JSON.stringify(args[index])} contains shell metacharacters` + ) + } + return undefined +} + +export const diagnosticsSkipReason = ( + error: unknown +): NonNullable => { + if (error instanceof TempFileError) return "temp-unwritable" + if (error instanceof ShellCommandError) return "unsafe-shell-command" + const code = (error as NodeJS.ErrnoException).code + if (code === "ENOENT") return "pyright-not-found" + if (code === "EACCES" || code === "EPERM" || code === "EROFS") return "pyright-not-executable" + return "invalid-output" +} + +const isMissingPath = (error: unknown): boolean => { + const code = (error as NodeJS.ErrnoException | undefined)?.code + return code === "ENOENT" || code === "ENOTDIR" +} + interface PyrightDiagnostic { readonly file: string readonly severity?: string @@ -91,13 +135,6 @@ const PYTHON_CELL_MAGICS = new Set([ "py" ]) -/** - * IPython magics and shell escapes are not valid Python. Blank them while - * preserving line and column positions so diagnostics on other lines stay - * correctly mapped. Python-bodied cell magics (`%%time`, `%%capture`, ...) - * keep their body; non-Python cell magics (`%%bash`, `%%html`, ...) blank the - * whole cell. - */ export const sanitizeNotebookText = (document: NotebookVirtualDocument): string => { const lines = document.text.split("\n") for (const cell of document.cells) { @@ -116,17 +153,11 @@ export const sanitizeNotebookText = (document: NotebookVirtualDocument): string /^\s*[%!]/.test(current) || /^\s*[^=#]+=\s*[%!]/.test(current) ) { - // A non-Python cell magic body has no Python suite structure, so a - // column-0 `pass` is the only safe replacement. Line magics inside a - // Python suite keep their indentation. lines[line] = blankWhole ? "pass".padEnd(current.length, " ") : replaceWithPass(current) continue } - // IPython help prefixes/suffixes (`?df.head`, `??df.head`, - // `df.head?`) are not valid Python. Replace the whole line with - // `pass` at the same indentation so suites stay valid. const code = stripPythonComment(current) if ( /^(\s*)\?{1,2}/.test(code) || @@ -158,10 +189,12 @@ const runPyright = ( resolve({ stdout: "", stderr: "", code: null, timedOut: false, aborted: true }) return } + const refusal = shellCommandRefusal(command, args, shell) + if (refusal !== undefined) { + reject(refusal) + return + } const detached = process.platform !== "win32" - // On Windows, .cmd shims require cmd.exe. Build a quoted command line - // instead of passing shell:true with unescaped argv (Node concatenates - // those verbatim, so a notebook path containing `&` could inject). let spawnCommand = command let spawnArgs: string[] = [...args] let useShell = shell @@ -186,10 +219,10 @@ const runPyright = ( windowsVerbatimArguments: verbatim, stdio: ["ignore", "pipe", "pipe"] }) - let stdout = "" - let stderr = "" let stdoutBytes = 0 let stderrBytes = 0 + const stdoutParts: string[] = [] + const stderrParts: string[] = [] const decoder = new StringDecoder("utf8") const stderrDecoder = new StringDecoder("utf8") let timedOut = false @@ -202,16 +235,13 @@ const runPyright = ( clearTimeout(timer) signal?.removeEventListener("abort", onAbort) resolve({ - stdout: stdout + decoder.end(), - stderr: stderr + stderrDecoder.end(), + stdout: stdoutParts.join("") + decoder.end(), + stderr: stderrParts.join("") + stderrDecoder.end(), code: exitCode, timedOut, aborted }) } - // Kill the whole process group. pyright may be a launcher that spawns a - // child which inherits stdout; killing only the parent leaves `close` - // pending until that grandchild exits. const killTree = () => { if (child.pid === undefined) return if (process.platform === "win32") { @@ -234,28 +264,22 @@ const runPyright = ( } signal?.addEventListener("abort", onAbort, { once: true }) child.stdout.on("data", (chunk: Buffer) => { - // Bound memory by bytes and decode through a stateful decoder so a - // multi-byte character split across chunks is not corrupted. if (stdoutBytes >= 8 * 1024 * 1024) return const take = chunk.subarray(0, 8 * 1024 * 1024 - stdoutBytes) stdoutBytes += take.length - stdout += decoder.write(take) + stdoutParts.push(decoder.write(take)) }) - // Drain stderr so a chatty/failing pyright cannot fill the pipe and - // hang until the timeout. Keep only a bounded prefix for diagnostics. child.stderr.on("data", (chunk: Buffer) => { if (stderrBytes >= 4_000) return const take = chunk.subarray(0, 4_000 - stderrBytes) stderrBytes += take.length - stderr += stderrDecoder.write(take) + stderrParts.push(stderrDecoder.write(take)) }) child.on("error", (error) => { clearTimeout(timer) signal?.removeEventListener("abort", onAbort) reject(error) }) - // `exit` fires even when a grandchild keeps the stdio pipe open. Give the - // pipe a short drain window, then settle regardless. child.on("exit", (code) => { exitCode = code setTimeout(finish, 50) @@ -312,7 +336,6 @@ const findOnPath = (name: string): string | undefined => { } return candidate } catch { - // keep looking } } } @@ -333,9 +356,6 @@ export const resolvePyrightCommand = ( "pyrightPath must be absolute or a bare command name resolved through PATH" ) } - // Resolve bare names to an absolute PATH entry so cmd.exe never searches - // the notebook/project cwd on Windows. If not found, do not fall back to a - // bare .cmd name with shell:true. const resolved = path.isAbsolute(requested) ? requested : findOnPath(defaultName ? "pyright" : requested) @@ -356,25 +376,56 @@ export const resolvePyrightCommand = ( const pyrightAvailability = new Map() const PYRIGHT_AVAILABILITY_TTL_MS = 60_000 +const PYRIGHT_AVAILABILITY_MAX = 32 + +const rememberPyrightAvailability = (key: string, ok: boolean): void => { + pyrightAvailability.set(key, { at: Date.now(), ok }) + // The TTL only makes an entry stale; without a size bound a long-lived host + // that sees many pyright paths keeps one entry per path forever. + if (pyrightAvailability.size > PYRIGHT_AVAILABILITY_MAX) { + let oldestKey: string | undefined + let oldestAt = Number.POSITIVE_INFINITY + for (const [candidate, entry] of pyrightAvailability) { + if (entry.at < oldestAt) { + oldestAt = entry.at + oldestKey = candidate + } + } + if (oldestKey !== undefined) pyrightAvailability.delete(oldestKey) + } +} + +export interface PyrightAvailabilityOptions { + readonly warningSink?: WarningSink | undefined +} -/** - * Cheap availability check used before asking permission or creating a temp - * file. Absolute paths are checked without spawning; a bare command is probed - * once per TTL. This avoids permission prompts when pyright is not installed. - */ export const isPyrightAvailable = async ( configured: string | undefined, timeoutMs = 5_000, - signal?: AbortSignal + signal?: AbortSignal, + options?: PyrightAvailabilityOptions ): Promise => { + const sink = options?.warningSink if (configured !== undefined && path.isAbsolute(configured)) { try { - if (!fs.statSync(configured).isFile()) return false + if (!fs.statSync(configured).isFile()) { + sink?.add( + warningFrom( + "python-probe", + new Error("the configured pyright path is not a file"), + `pyrightPath=${configured}` + ) + ) + return false + } if (process.platform !== "win32") { fs.accessSync(configured, fsConstants.X_OK) } return true - } catch { + } catch (error) { + sink?.add( + warningFrom("python-probe", error, `pyrightPath=${configured}`) + ) return false } } @@ -384,7 +435,12 @@ export const isPyrightAvailable = async ( const resolved = resolvePyrightCommand(configured) command = resolved.command shell = resolved.shell - } catch { + } catch (error) { + if (configured !== undefined && configured !== "pyright") { + sink?.add( + warningFrom("python-probe", error, `pyrightPath=${configured}`) + ) + } return false } const key = `${command}:${shell ? "shell" : "direct"}` @@ -404,13 +460,14 @@ export const isPyrightAvailable = async ( shell ) ok = outcome.code === 0 && !outcome.timedOut && !outcome.aborted - // A timeout/abort says nothing about availability; do not suppress - // diagnostics for a full TTL because of a transient interruption. if (outcome.timedOut || outcome.aborted) cacheable = false - } catch { + } catch (error) { ok = false + if (error instanceof ShellCommandError) { + sink?.add(warningFrom("python-probe", error, "checking pyright availability")) + } } - if (cacheable) pyrightAvailability.set(key, { at: Date.now(), ok }) + if (cacheable) rememberPyrightAvailability(key, ok) return ok } @@ -419,15 +476,10 @@ const diagnosticHash = (filePath: string): string => { try { real = realpathSync(filePath) } catch { - // Newly created notebooks still need a stable identity. } return createHash("sha256").update(real).digest("hex").slice(0, 16) } - /** - * A stable temp path keeps an "always allow" edit grant meaningful. The - * content is rewritten on each run and removed afterwards. - */ const realFilePath = (filePath: string): string => { try { return realpathSync(filePath) @@ -442,7 +494,6 @@ export const diagnosticTempPath = (filePath: string): string => `opencode-ipynb-diag-${diagnosticHash(filePath)}.py` ) -/** Fallback used when the notebook directory is not writable. */ export const diagnosticFallbackTempPath = (filePath: string): string => path.join( os.tmpdir(), @@ -519,18 +570,11 @@ const endsWithOpenConstruct = (source: string): boolean => { return last.endsWith(":") || last.endsWith("\\") || /[([{]$/.test(last) } -/** - * A syntax error caused by an incomplete construct in one cell is often - * reported at the first line of the next cell. Map that boundary error back - * when the previous cell clearly ends with an open construct. - */ const remapCellBoundary = ( document: NotebookVirtualDocument, position: { cellIndex: number; line: number; character: number }, rule?: string ): { cellIndex: number; line: number; character: number } => { - // Pyright syntax errors have no rule; semantic diagnostics must stay in - // the cell where they were reported. if (rule !== undefined) return position if ( position.line !== 0 || @@ -539,12 +583,12 @@ const remapCellBoundary = ( ) { return position } - const current = document.cells.find((cell) => cell.cellIndex === position.cellIndex) - if (current === undefined) return position - const previous = document.cells.find( - (cell) => cell.cellIndex < position.cellIndex && cell.endLine === current.startLine - ) - if (previous === undefined) return position + const around = cellsAroundIndex(document, position.cellIndex) + if (around === undefined) return position + const previous = around.previous + if (previous === undefined || previous.endLine !== around.current.startLine) { + return position + } if (endsWithOpenConstruct(previous.text)) { const last = lastSignificantLine(previous.text) return { @@ -563,19 +607,41 @@ export const diagnoseNotebook = async ( if (options.signal?.aborted) { return { filePath, diagnostics: [], text: "", skipped: "aborted" } } - const directory = path.dirname(realFilePath(filePath)) + const collected: Warning[] = [] + const record = (warning: Warning): void => { + collected.push(warning) + options.warningSink?.add(warning) + } + let resolvedFile = filePath + try { + resolvedFile = realpathSync(filePath) + } catch (error) { + record(warningFrom("path-resolution", error, `resolving ${filePath}`)) + } + const directory = path.dirname(resolvedFile) const explicitTemp = options.tempFilePath const owned = options.ownedTempFile === true || explicitTemp === undefined let tempFile = explicitTemp ?? diagnosticTempPath(filePath) - return withDiagnosticLock(tempFile, async () => { + const result: NotebookDiagnosticsResult = await withDiagnosticLock(tempFile, async () => { if (options.signal?.aborted) { - return { filePath, diagnostics: [], text: "", skipped: "aborted" } + return { filePath, diagnostics: [], text: "", skipped: "aborted" as const } + } + const closeHandle = async ( + handle: Awaited>, + file: string + ): Promise => { + await handle.close().catch((error: unknown) => { + record(warningFrom("temp-unlink", error, `closing ${file}`)) + }) } const openTemp = async (file: string): Promise => { if (!owned) { - // A caller-supplied path is never truncated or deleted: fail if it - // already exists, and only clean up a file we created ourselves. - const existing = await fsp.lstat(file).catch(() => undefined) + const existing = await fsp.lstat(file).catch((error: unknown) => { + if (!isMissingPath(error)) { + record(warningFrom("path-resolution", error, `inspecting ${file}`)) + } + return undefined + }) if (existing !== undefined) { throw new Error(`refusing to overwrite caller-supplied temp file: ${file}`) } @@ -586,12 +652,19 @@ export const diagnoseNotebook = async ( mode: 0o600 }) } catch (error) { - await fsp.rm(file, { force: true }).catch(() => {}) + await fsp.rm(file, { force: true }).catch((cleanupError: unknown) => { + record(warningFrom("temp-unlink", cleanupError, `left ${file}`)) + }) throw error } return } - const existing = await fsp.lstat(file).catch(() => undefined) + const existing = await fsp.lstat(file).catch((error: unknown) => { + if (!isMissingPath(error)) { + record(warningFrom("path-resolution", error, `inspecting ${file}`)) + } + return undefined + }) if (existing?.isSymbolicLink()) { throw new TempFileError(`refusing to follow a symlink at ${file}`) } @@ -602,8 +675,6 @@ export const diagnoseNotebook = async ( throw new TempFileError(`refusing to open a hardlinked temp file at ${file}`) } if (existing !== undefined) { - // A predictable temp path on a shared /tmp must not be attacker-owned - // or world/group-readable, or notebook source could be disclosed. const uid = typeof process.getuid === "function" ? process.getuid() : undefined if (uid !== undefined && existing.uid !== uid) { throw new TempFileError(`refusing a temp file owned by another user: ${file}`) @@ -628,7 +699,7 @@ export const diagnoseNotebook = async ( const opened = await handle.stat() const uid = typeof process.getuid === "function" ? process.getuid() : undefined if (!opened.isFile() || opened.nlink > 1) { - await handle.close().catch(() => {}) + await closeHandle(handle, file) throw new TempFileError(`refusing to write a linked/non-regular temp file at ${file}`) } if ( @@ -637,19 +708,19 @@ export const diagnoseNotebook = async ( existing !== undefined && (opened.mode & 0o077) !== 0) ) { - await handle.close().catch(() => {}) + await closeHandle(handle, file) throw new TempFileError(`refusing a temp file with unsafe ownership/mode: ${file}`) } - // Truncate only after fstat proved nlink === 1; O_TRUNC before the - // check would already have damaged a swapped-in hardlink victim. await handle.truncate(0) await handle.writeFile(text, "utf8") } catch (error) { - await handle.close().catch(() => {}) - await fsp.rm(file, { force: true }).catch(() => {}) + await closeHandle(handle, file) + await fsp.rm(file, { force: true }).catch((cleanupError: unknown) => { + record(warningFrom("temp-unlink", cleanupError, `left ${file}`)) + }) throw error } - await handle.close() + await closeHandle(handle, file) } const text = sanitizeNotebookText(document) @@ -667,8 +738,6 @@ export const diagnoseNotebook = async ( error instanceof Error ? error.message : String(error) ) } - // Read-only notebook directory: fall back to the system temp dir. - // Imports may be less accurate, but syntax/type errors still work. if (options.requestFallbackPermission !== undefined) { await options.requestFallbackPermission() } @@ -720,9 +789,6 @@ export const diagnoseNotebook = async ( if (outcome.timedOut) { return { filePath, diagnostics: [], text: "", skipped: "timeout" } } - // Pyright uses 0 = clean, 1 = type errors, >=2 = fatal/configuration - // failure. Fatal exits can still print valid JSON with an empty - // diagnostics array; never report that as a clean notebook. if (outcome.code !== null && outcome.code > 1) { return { filePath, diagnostics: [], text: "", skipped: "invalid-output" } } @@ -734,8 +800,6 @@ export const diagnoseNotebook = async ( } const analyzed = parsed.summary?.filesAnalyzed if (typeof analyzed === "number" && analyzed === 0) { - // A pyright exclude/config can silently skip the sidecar. That is - // not a clean notebook. return { filePath, diagnostics: [], text: "", skipped: "not-analyzed" } } if (process.env.OPENCODE_IPYNB_DIAG_DEBUG === "1") { @@ -750,6 +814,24 @@ export const diagnoseNotebook = async ( ? item.file : path.resolve(directory, item.file) if (itemPath !== path.resolve(tempFile)) continue + // pyright omits `range` for a file-level report ("Code is too complex to + // analyze", syntax errors in the file prologue). Dereferencing it threw, + // the throw was swallowed, and EVERY diagnostic for the notebook was + // lost. Report those without a position instead of dropping the batch. + if (item.range === undefined) { + diagnostics.push({ + cellIndex: -1, + line: 1, + character: 1, + endLine: 1, + endCharacter: 1, + severity: "error", + message: item.message ?? "pyright reported a file-level error", + ...(item.rule === undefined ? {} : { rule: item.rule }), + fileLevel: true + }) + continue + } const rawMapped = toCellPosition( document, item.range.start.line, @@ -783,8 +865,6 @@ export const diagnoseNotebook = async ( ...(item.rule === undefined ? {} : { rule: item.rule.slice(0, 200) }) }) } - // Pyright can exit 0 and still warn that the configuration was - // rejected. An empty diagnostics list then does not mean clean. if ( diagnostics.length === 0 && /config[\s\S]{0,120}(error|must|invalid|unrecognized|unsupported)/i.test( @@ -801,23 +881,22 @@ export const diagnoseNotebook = async ( } } catch (error) { if (error instanceof PermissionDeniedError) throw error - const code = (error as NodeJS.ErrnoException).code + if (error instanceof ShellCommandError) { + record(warningFrom("shell-command", error, "running pyright for diagnostics")) + } return { filePath, diagnostics: [], text: "", - skipped: - error instanceof TempFileError - ? "temp-unwritable" - : code === "ENOENT" - ? "pyright-not-found" - : code === "EACCES" || code === "EPERM" || code === "EROFS" - ? "pyright-not-executable" - : "invalid-output" + skipped: diagnosticsSkipReason(error) } } finally { - // Never delete a caller-supplied path that we did not create. - if (wroteTemp) await fsp.rm(tempFile, { force: true }).catch(() => {}) + if (wroteTemp) { + await fsp.rm(tempFile, { force: true }).catch((error: unknown) => { + record(warningFrom("temp-unlink", error, `left ${tempFile}`)) + }) + } } }) + return collected.length === 0 ? result : { ...result, warnings: collected } } diff --git a/src/notebook-hooks.ts b/src/notebook-hooks.ts index aad0333..594d12c 100644 --- a/src/notebook-hooks.ts +++ b/src/notebook-hooks.ts @@ -1,8 +1,3 @@ -/** - * Pure helpers for the notebook `execute.after` hook. Keeping the tool-name - * normalization and changed/no-op rules here makes the plugin entrypoint - * mostly lifecycle wiring and gives the tests a small unit to target. - */ export const notebookMutatingTools = new Set([ "ipynb_edit", diff --git a/src/plugin-options.ts b/src/plugin-options.ts index ee45abb..fec5594 100644 --- a/src/plugin-options.ts +++ b/src/plugin-options.ts @@ -72,10 +72,6 @@ export const PluginOptionsSchema = z.object({ }) export type PluginOptions = z.infer -/** - * Resolve the interpreter used for execution and diagnostics. The explicit - * environment variable wins over the plugin option, matching the README. - */ const findExecutable = (name: string): string | undefined => { const dirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean) const names = @@ -92,7 +88,6 @@ const findExecutable = (name: string): string | undefined => { if (process.platform !== "win32") fs.accessSync(candidate, fs.constants.X_OK) return candidate } catch { - // keep looking } } } @@ -107,10 +102,6 @@ export const resolvePythonPath = ( env !== undefined && env.length > 0 ? env : options.pythonPath if (value === undefined || value.trim().length === 0) return undefined const trimmed = value.trim() - // Path-like values must be absolute so the permission resource and the - // spawned executable cannot diverge. Bare names are resolved through PATH - // here, because pyright's --pythonpath resolves relative values against the - // notebook directory. if (!path.isAbsolute(trimmed) && /[\\/]/.test(trimmed)) { throw new Error( "pythonPath must be absolute or a bare command name resolved through PATH" diff --git a/src/plugin-v2.ts b/src/plugin-v2.ts index 53d2a16..99275c7 100644 --- a/src/plugin-v2.ts +++ b/src/plugin-v2.ts @@ -1,4 +1,9 @@ import { z } from "zod" +import { + makeWarningSink, + type Warning, + type WarningSink +} from "./utils/warnings.js" import type { Plugin } from "@opencode/plugin" import type { AnyToolDefinition, @@ -39,10 +44,61 @@ export interface V2ToolResult { readonly metadata?: Record } -const jsonSchemaFor = (definition: AnyToolDefinition): V2ToolInfo["input"] => - z.toJSONSchema(z.object(definition.args), { - io: "input" - }) as unknown as V2ToolInfo["input"] +const conditionalRequirements: Record>> = { + ipynb_read: [ + { required: ["cellIndex"] }, + { required: ["start", "end"] } + ], + ipynb_outputs: [ + { + properties: { operation: { enum: ["read", "read_error", "clear_cell"] } }, + required: ["cellIndex"] + } + ] +} + +const jsonSchemaFor = ( + name: string, + definition: AnyToolDefinition +): V2ToolInfo["input"] => { + const schema = z.object(definition.args) + const generated = z.toJSONSchema(schema, { io: "input" }) as Record + const strict = z.toJSONSchema(schema.strict(), { io: "input" }) as { + additionalProperties?: boolean + } + const alternatives = conditionalRequirements[name] + const structural = + alternatives === undefined + ? {} + : name === "ipynb_read" + ? { + anyOf: [ + { required: ["cellIndex"], not: { anyOf: [{ required: ["start"] }, { required: ["end"] }] } }, + { required: ["start", "end"], not: { required: ["cellIndex"] } } + ] + } + : { + anyOf: [ + { + properties: { + operation: { enum: ["read", "read_error", "clear_cell"] } + }, + required: ["operation", "cellIndex"] + }, + { + properties: { + operation: { enum: ["list", "clear_all"] } + }, + required: ["operation"] + } + ] + } + return { + ...generated, + ...(strict.additionalProperties === false ? { additionalProperties: false } : {}), + ...structural + } as unknown as V2ToolInfo["input"] +} const toFileContent = (attachment: ToolAttachment): V2FileContent => { const base: V2FileContent = { @@ -92,15 +148,11 @@ export const toV2Result = (result: ToolResult): V2ToolResult => { return Object.keys(metadata).length > 0 ? { content, metadata } : { content } } -/** - * V2 custom tools do not receive the V1 ToolContext shape. Adapt the V2 tool - * execution context, and route ctx.ask through the V2 permission domain so - * every write and execution still prompts (or is denied by explicit rules). - */ export const toToolContext = ( pluginContext: Plugin.Context, context: V2ToolContext, - pluginOptions: unknown + pluginOptions: unknown, + warningSink?: WarningSink ): ToolContext => ({ sessionID: context.sessionID, messageID: context.messageID, @@ -110,6 +162,7 @@ export const toToolContext = ( abort: context.signal, pluginOptions, pluginScope: pluginContext, + warningSink, metadata: (input) => { void context .progress({ @@ -119,8 +172,6 @@ export const toToolContext = ( .catch(() => {}) }, ask: async (input) => { - // V2 calls the execution permission "shell". Keep accepting the internal - // legacy name "bash" so older custom tools keep working. const action = input.permission === "bash" ? "shell" : input.permission await pluginContext.permission.assert({ sessionID: context.sessionID as PermissionAssertInput["sessionID"], @@ -138,24 +189,52 @@ export const toToolContext = ( } }) +const appendWarnings = (result: unknown, warnings: ReadonlyArray) => { + const rendered = warnings + .map( + (warning) => + `warning [${warning.source}]: ${warning.message}` + + (warning.detail === undefined ? "" : ` (${warning.detail})`) + ) + .join("\n") + if (typeof result === "string") return `${result}\n\n${rendered}` + if (result !== null && typeof result === "object") { + const record = result as { output?: unknown; metadata?: Record } + const output = + typeof record.output === "string" + ? `${record.output}\n\n${rendered}` + : rendered + return { + ...record, + output, + metadata: { ...(record.metadata ?? {}), warnings } + } + } + return result +} + export const toV2Tool = ( pluginContext: Plugin.Context, registration: V2ToolRegistration, - pluginOptions: unknown = pluginContext.options + pluginOptions: unknown = pluginContext.options, + warningSink?: WarningSink ): V2ToolInfo => { - const argsSchema = z.object(registration.definition.args) + const argsSchema = z.object(registration.definition.args).strict() return { name: registration.name, description: registration.definition.description, - input: jsonSchemaFor(registration.definition), + input: jsonSchemaFor(registration.name, registration.definition), options: { - // Native tools (not Code Mode) so permissions surface on the tool call. codemode: false, ...(registration.permission === undefined ? {} : { permission: registration.permission }) }, async execute(rawInput, context) { + if (context.signal?.aborted) { + const message = "the request was cancelled; nothing was changed" + return { content: `Error: ${message}`, metadata: { error: true, message } } + } const parsed = argsSchema.safeParse(rawInput ?? {}) if (!parsed.success) { const message = parsed.error.issues @@ -163,11 +242,14 @@ export const toV2Tool = ( .join("; ") return { content: `Error: ${message}`, metadata: { error: true, message } } } + const sink = warningSink ?? makeWarningSink() const result = await registration.definition.execute( parsed.data as never, - toToolContext(pluginContext, context, pluginOptions) + toToolContext(pluginContext, context, pluginOptions, sink) ) - return toV2Result(result) + const warnings = sink.drain() + if (warnings.length === 0) return toV2Result(result) + return toV2Result(appendWarnings(result, warnings) as never) } } } diff --git a/src/plugin.ts b/src/plugin.ts index 6f3825e..4973002 100644 --- a/src/plugin.ts +++ b/src/plugin.ts @@ -4,6 +4,7 @@ import { disposeSharedKernelManager, resolveOptionsFromEnv } from "./services/in import { registerV2Tools } from "./plugin-v2.js" import { parsePluginOptions } from "./plugin-options.js" import { + resolvePyrightCommand, diagnoseNotebook, diagnosticFallbackTempPath, diagnosticTempPath, @@ -21,6 +22,12 @@ import { refreshMaterializedDocument } from "./virtual-materialize.js" import { NotebookRpc } from "./rpc.js" +import { + bestEffort, + makeWarningSink, + warningFrom, + type Warning +} from "./utils/warnings.js" import { v2ToolRegistrations } from "./registrations.js" import { appendResultText, @@ -31,15 +38,24 @@ import { type MutableResult } from "./notebook-hooks.js" +const MAX_NOTEBOOK_WARNINGS = 50 + +const attachNotebookWarnings = ( + result: MutableResult | undefined, + warnings: ReadonlyArray +): void => { + if (result === undefined || warnings.length === 0) return + const current = result.metadata?.notebookWarnings + const existing = Array.isArray(current) ? (current as ReadonlyArray) : [] + result.metadata = { + ...(result.metadata ?? {}), + notebookWarnings: [...existing, ...warnings].slice(-MAX_NOTEBOOK_WARNINGS) + } +} + const plugin: Plugin.Plugin = { id: "opencode-ipynb", async setup(context) { - // V2 passes per-plugin-instance options through setup. The adapter puts - // them on the tool context instead of process.env, so multiple projects - // in one OpenCode server cannot leak settings into each other. Explicit - // env vars still take precedence when options are resolved. - // Validate and normalize options once per plugin instance. Invalid - // options fail setup instead of being silently ignored at tool time. const options = parsePluginOptions(context.options) const effectiveOptions = resolveOptionsFromEnv(options) const registration = await registerV2Tools( @@ -89,9 +105,11 @@ const plugin: Plugin.Plugin = { if (!changedNotebook(event.tool, event.input, event.result?.metadata)) return const filePath = (event.input as { filePath?: unknown } | undefined)?.filePath if (typeof filePath !== "string") return - // RPC invalidation is fire-and-forget. Diagnostics below are awaited - // on purpose so the agent sees errors in the same tool result. - void rpcRegistration.events.emit("changed", { filePath }).catch(() => {}) + const sink = makeWarningSink() + const result = event.result as MutableResult | undefined + void rpcRegistration.events.emit("changed", { filePath }).catch((error) => { + sink.add(warningFrom("cleanup", error, "emitting the changed event")) + }) const name = toolName(event.tool) const absoluteForMaterialized = path.isAbsolute(filePath) @@ -104,7 +122,8 @@ const plugin: Plugin.Plugin = { codeChange && (await hasMaterializedDocument( context.location.directory, - absoluteForMaterialized + absoluteForMaterialized, + { warningSink: sink } )) ) { document = await loadDocument(filePath) @@ -117,12 +136,12 @@ const plugin: Plugin.Plugin = { context.location.project.directory ]) await context.permission.assert({ - sessionID: event.sessionID as never, - agent: event.agent as never, + sessionID: event.sessionID, + agent: event.agent, source: { type: "tool", - messageID: event.messageID as never, - id: event.id as never + messageID: event.messageID, + id: event.id }, action: "edit", resources: [...sidecarPaths], @@ -132,12 +151,12 @@ const plugin: Plugin.Plugin = { operation: "materialize-refresh" } }) - await refreshMaterializedDocument(document, context.location.directory) + await refreshMaterializedDocument(document, context.location.directory, { + warningSink: sink + }) } } catch (error) { - // Refreshing the sidecar is best-effort, but a stale navigation file - // is user-visible: report it in the same tool result. - const result = event.result as MutableResult | undefined + sink.add(warningFrom("sidecar-cleanup", error, "refreshing the notebook sidecar")) if (result) { const message = error instanceof Error ? error.message : String(error) @@ -149,9 +168,13 @@ const plugin: Plugin.Plugin = { } if (effectiveOptions.lspDiagnostics === false || !diagnosableTools.has(name)) { + attachNotebookWarnings(result, sink.drain()) + return + } + if (!codeChange) { + attachNotebookWarnings(result, sink.drain()) return } - if (!codeChange) return let permissionDenied = false try { document ??= await loadDocument(filePath) @@ -175,12 +198,12 @@ const plugin: Plugin.Plugin = { ]) try { await context.permission.assert({ - sessionID: event.sessionID as never, - agent: event.agent as never, + sessionID: event.sessionID, + agent: event.agent, source: { type: "tool", - messageID: event.messageID as never, - id: event.id as never + messageID: event.messageID, + id: event.id }, action: "lsp", resources: [...lspPaths], @@ -191,23 +214,54 @@ const plugin: Plugin.Plugin = { permissionDenied = true throw error } - // Only spawn pyright after the host approved the lsp action. + let pyrightBinary: string | undefined + try { + pyrightBinary = resolvePyrightCommand(effectiveOptions.pyrightPath).command + } catch { + pyrightBinary = undefined + } + if ( + pyrightBinary !== undefined && + !lspPaths.includes(pyrightBinary) + ) { + try { + await context.permission.assert({ + sessionID: event.sessionID, + agent: event.agent, + source: { + type: "tool", + messageID: event.messageID, + id: event.id + }, + action: "lsp", + resources: [pyrightBinary], + save: [], + metadata: { filePath: document.filePath, operation: "pyright-binary" } + }) + } catch (error) { + permissionDenied = true + throw error + } + } if ( !(await isPyrightAvailable( effectiveOptions.pyrightPath, - effectiveOptions.diagnosticsTimeoutMs + effectiveOptions.diagnosticsTimeoutMs, + undefined, + { warningSink: sink } )) ) { + attachNotebookWarnings(result, sink.drain()) return } try { await context.permission.assert({ - sessionID: event.sessionID as never, - agent: event.agent as never, + sessionID: event.sessionID, + agent: event.agent, source: { type: "tool", - messageID: event.messageID as never, - id: event.id as never + messageID: event.messageID, + id: event.id }, action: "edit", resources: [...tempPaths], @@ -224,12 +278,12 @@ const plugin: Plugin.Plugin = { requestFallbackPermission: async () => { try { await context.permission.assert({ - sessionID: event.sessionID as never, - agent: event.agent as never, + sessionID: event.sessionID, + agent: event.agent, source: { type: "tool", - messageID: event.messageID as never, - id: event.id as never + messageID: event.messageID, + id: event.id }, action: "edit", resources: [...fallbackPaths], @@ -257,9 +311,9 @@ const plugin: Plugin.Plugin = { ? {} : { pythonPath: document.pythonPath }), pyrightPath: effectiveOptions.pyrightPath, - timeoutMs: effectiveOptions.diagnosticsTimeoutMs + timeoutMs: effectiveOptions.diagnosticsTimeoutMs, + warningSink: sink }) - const result = event.result as MutableResult | undefined if (!result) return if (diagnostics.text.length > 0) appendResultText(result, diagnostics.text) else if ( @@ -279,31 +333,46 @@ const plugin: Plugin.Plugin = { ) } } - } catch { - // Diagnostics are best-effort; a broken pyright or denied permission - // must not fail the edit. Make a denial visible instead of silently - // pretending the notebook was checked. + } catch (error) { if (permissionDenied) { - const result = event.result as MutableResult | undefined if (result) { appendResultText( result, "Notebook diagnostics skipped: permission denied." ) } + } else { + sink.add(warningFrom("python-probe", error, "running notebook diagnostics")) + if (result) { + appendResultText( + result, + `Notebook diagnostics failed: ${ + error instanceof Error ? error.message : String(error) + }` + ) + } } + } finally { + attachNotebookWarnings(result, sink.drain()) } }) return async () => { + const sink = makeWarningSink() try { - await hookRegistration.dispose().catch(() => {}) - await rpcRegistration.dispose().catch(() => {}) - await registration.dispose().catch(() => {}) - await cleanupVirtualDocuments(context.location.directory).catch(() => {}) + await bestEffort(sink, "cleanup", "hook dispose", () => hookRegistration.dispose()) + await bestEffort(sink, "cleanup", "rpc dispose", () => rpcRegistration.dispose()) + await bestEffort(sink, "cleanup", "tool dispose", () => registration.dispose()) + await bestEffort(sink, "sidecar-cleanup", "virtual documents", () => + cleanupVirtualDocuments(context.location.directory, { warningSink: sink }) + ) } finally { - // Kill every live warm kernel even when a plugin contribution fails - // to dispose. A sidecar cleanup error must not leak Python processes. + for (const warning of sink.drain()) { + console.warn( + `[opencode-ipynb] ${warning.source}: ${warning.message}` + + (warning.detail === undefined ? "" : ` (${warning.detail})`) + ) + } await disposeSharedKernelManager(context) } } diff --git a/src/registrations.ts b/src/registrations.ts index a9465d1..3b4dfcf 100644 --- a/src/registrations.ts +++ b/src/registrations.ts @@ -32,11 +32,6 @@ export const toolDefinitions: Record = { ipynb_lsp: ipynbLspTool } -// The permission name declared on a V2 tool is matched against the user's -// permission rules. Mutating tools map to "edit"; execution maps to "shell"; -// the mixed LSP tool maps to "lsp" (its materialize branch additionally asks -// for edit on the sidecar path). Per-call approval still goes through -// ctx.permission.assert. export const permissionByTool: Record = { ipynb_inspect: "read", ipynb_read: "read", diff --git a/src/rpc.ts b/src/rpc.ts index fca375c..03ae49c 100644 --- a/src/rpc.ts +++ b/src/rpc.ts @@ -33,13 +33,6 @@ const documentSchema = { additionalProperties: false } as const -/** - * Public RPC contract for notebook/LSP integration. - * - * Other plugins can import this contract from `opencode-ipynb/rpc`, call - * `document` to get a provider-agnostic virtual document, and subscribe to - * `changed` to refresh diagnostics after the plugin edits a notebook. - */ export const NotebookRpc = { id: "opencode-ipynb", methods: { diff --git a/src/services/KernelManager.ts b/src/services/KernelManager.ts index 6b8c3f0..64c1182 100644 --- a/src/services/KernelManager.ts +++ b/src/services/KernelManager.ts @@ -3,6 +3,7 @@ import { killWindowsTree } from "../utils/windows.js" import { promises as fsp, realpathSync } from "node:fs" import { Effect } from "effect" import { StringDecoder } from "node:string_decoder" +import { randomUUID } from "node:crypto" import { PythonRunnerError, type NotebookError } from "../domain/errors.js" import { RunResponseSchema, @@ -11,16 +12,20 @@ import { } from "../domain/execution.js" import { helperSpawnEnv } from "./PythonService.js" import { MAX_HELPER_STDOUT_BYTES } from "../utils/limits.js" +import { + type Warning, + type WarningSink, + warningFrom +} from "../utils/warnings.js" -// --------------------------------------------------------------------------- -// KernelManager: long-lived Python subprocess per notebook path. -// --------------------------------------------------------------------------- export interface KernelManagerOptions { readonly pythonPath: string readonly helperPath: string readonly workingDirectory: string | undefined readonly defaultTimeoutMs: number + readonly warningSink?: WarningSink + readonly sinkTarget?: { sink?: WarningSink | undefined } } export interface KernelRuntimeOptions { @@ -34,6 +39,7 @@ export interface KernelInfo { readonly lastUsedAt: number readonly requestsHandled: number readonly stderrTail: string + readonly warnings?: ReadonlyArray } export interface KernelManagerStats { @@ -44,19 +50,24 @@ export interface KernelManagerStats { interface PendingRequest { resolve: (response: RunResponse) => void reject: (err: PythonRunnerError) => void - timer: NodeJS.Timeout + timer: NodeJS.Timeout | undefined cleanup?: () => void + sink?: WarningSink | undefined + nonce: string } interface KernelState { proc: ChildProcess filePath: string + reportedPath: string pythonPath: string helperPath: string requestedKernel: string | undefined pid: number kernelPid: number | undefined nextId: number + inflight: number + nonceRequired: boolean pending: Map readyPromise: Promise resolveReady: () => void @@ -65,12 +76,14 @@ interface KernelState { lastUsed: number requestsHandled: number stderrTail: string[] + warnings: Warning[] alive: boolean startedAt: number shutdownRequestId: number | undefined } const STDERR_TAIL_MAX = 20 +const KERNEL_WARNINGS_MAX = 20 interface Deferred { readonly promise: Promise @@ -78,9 +91,6 @@ interface Deferred { readonly reject: (e: E) => void } -// Minimal deferred (resolve/reject are always assigned synchronously in the -// executor). Equivalent to Promise.withResolvers but typed against a custom -// error type without resorting to ``unknown``. const createDeferred = (): Deferred => { let resolve!: (a: A) => void let reject!: (e: E) => void @@ -91,10 +101,6 @@ const createDeferred = (): Deferred => { return { promise, resolve, reject } } -// Sentinel resolved to the pending shutdown handler when the kernel exits -// cleanly. The shutdown call site ignores the value (`sendShutdown` always -// resolves its outer promise), so the only requirement is that it satisfies -// the RunResponse type. Keep it minimal: zero cells, zero duration. const EMPTY_SHUTDOWN_RESPONSE = { success: true, executedCells: [] as ReadonlyArray, @@ -102,11 +108,12 @@ const EMPTY_SHUTDOWN_RESPONSE = { outputs: [] as ReadonlyArray } as unknown as RunResponse -const killPidTree = ( +export const killPidTree = ( pid: number | undefined, - signal: NodeJS.Signals = "SIGTERM" + signal: NodeJS.Signals = "SIGTERM", + notify?: (error: unknown) => void ): void => { - if (pid === undefined || pid <= 0) return + if (pid === undefined || pid <= 1) return if (process.platform === "win32") { killWindowsTree(pid) return @@ -116,8 +123,10 @@ const killPidTree = ( } catch { try { process.kill(pid, signal) - } catch { - // already gone + } catch (directError) { + if ((directError as NodeJS.ErrnoException).code !== "ESRCH") { + notify?.(directError) + } } } } @@ -125,9 +134,10 @@ const killPidTree = ( const killProcessTree = ( proc: ChildProcess, signal: NodeJS.Signals = "SIGTERM", - kernelPid?: number + kernelPid?: number, + notify?: (error: unknown) => void ): void => { - killPidTree(kernelPid, signal) + killPidTree(kernelPid, signal, notify) if (proc.pid === undefined) return if (process.platform === "win32") { killWindowsTree(proc.pid) @@ -138,8 +148,10 @@ const killProcessTree = ( } catch { try { proc.kill(signal) - } catch { - // proc may already be dead; ignore. + } catch (directError) { + if ((directError as NodeJS.ErrnoException).code !== "ESRCH") { + notify?.(directError) + } } } } @@ -196,9 +208,50 @@ const withTimeout = ( export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShape => { const states = new Map() + const canonicalAliases = new Map() + + const forgetState = (filePath: string): void => { + states.delete(filePath) + for (const [alias, target] of canonicalAliases) { + if (target === filePath) canonicalAliases.delete(alias) + } + } const kernelLocks = new Map>() + const sinkTarget = opts.sinkTarget ?? { sink: opts.warningSink } + const currentSink = (): WarningSink | undefined => sinkTarget.sink + const reported = new Set() let totalRequests = 0 + const record = (state: KernelState, warning: Warning): void => { + const key = `${state.filePath}|${warning.source}|${warning.detail ?? warning.message}` + if (reported.has(key)) return + if (reported.size >= KERNEL_WARNINGS_MAX * 5) reported.clear() + reported.add(key) + if (state.warnings.length >= KERNEL_WARNINGS_MAX) state.warnings.shift() + state.warnings.push(warning) + const sink = currentSink() + if (sink !== undefined) sink.add(warning) + for (const pending of state.pending.values()) { + if (pending.sink !== undefined && pending.sink !== sink) pending.sink.add(warning) + } + } + + const stopKernelIfIdle = (filePath: string, state: KernelState): void => { + if (state.pending.size > 0 || state.inflight > 0) return + stopKernelInBackground(filePath) + } + + const stopKernelInBackground = (filePath: string): void => { + void killKernel(filePath).catch((error: unknown) => { + currentSink()?.add(warningFrom("cleanup", error, `stopping the warm kernel for ${filePath}`)) + }) + } + + const killFailure = + (state: KernelState): ((error: unknown) => void) => + (error) => + record(state, warningFrom("cleanup", error, "killing the kernel process tree")) + const withKernelLock = async ( key: string, task: () => Promise @@ -259,24 +312,21 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap stdio: ["pipe", "pipe", "pipe"] } ) - // Swallow EPIPE on stdin; without a listener a helper that exits during - // startup would emit an uncaught stream error. Pending requests are - // failed by the close/error handlers below. proc.stdin?.on("error", () => {}) const startedAt = Date.now() - // Build the ready-deferred promise up front so we can store the - // resolve/reject closures on the state in one place — no second pass - // after construction to wire them up. const readyDeferred = createDeferred() const state: KernelState = { proc, filePath, + reportedPath: filePath, pythonPath: runtime.pythonPath, helperPath: runtime.helperPath, requestedKernel, pid: proc.pid ?? -1, kernelPid: undefined, nextId: 1, + inflight: 0, + nonceRequired: false, pending: new Map(), readyPromise: readyDeferred.promise, resolveReady: readyDeferred.resolve, @@ -285,6 +335,7 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap lastUsed: startedAt, requestsHandled: 0, stderrTail: [], + warnings: [], alive: true, startedAt, shutdownRequestId: undefined @@ -292,8 +343,10 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap const handleLine = (line: string): void => { if (!line.trim()) return - if (line.length > MAX_HELPER_STDOUT_BYTES) { + if (Buffer.byteLength(line, "utf8") > MAX_HELPER_STDOUT_BYTES) { for (const handler of state.pending.values()) { + clearTimeout(handler.timer) + handler.cleanup?.() handler.reject( new PythonRunnerError({ message: `kernel response exceeded ${MAX_HELPER_STDOUT_BYTES} bytes`, @@ -307,15 +360,30 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap let msg: unknown try { msg = JSON.parse(line) - } catch { + } catch (error) { + record( + state, + warningFrom("python-probe", error, `ignored non-JSON kernel output: ${line.slice(0, 200)}`) + ) + return + } + if (!msg || typeof msg !== "object") { + record( + state, + warningFrom( + "python-probe", + new Error("kernel emitted a non-object JSON line"), + `ignored: ${line.slice(0, 200)}` + ) + ) return } - if (!msg || typeof msg !== "object") return const m = msg as Record if (!state.readyResolved && m.ready === true) { if (typeof m.kernelPid === "number" && m.kernelPid > 0) { state.kernelPid = m.kernelPid } + state.nonceRequired = m.nonceVersion === 1 state.readyResolved = true state.resolveReady() return @@ -338,6 +406,20 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap if (id === undefined) return const handler = state.pending.get(id) if (!handler) return + if ( + state.nonceRequired && + (typeof m.nonce !== "string" || m.nonce !== handler.nonce) + ) { + record( + state, + warningFrom( + "python-probe", + new Error("ignored a kernel line whose nonce does not match the request"), + `id=${id}` + ) + ) + return + } state.pending.delete(id) clearTimeout(handler.timer) handler.cleanup?.() @@ -360,14 +442,19 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap detail: "" }) ) + if ( + ename === "KernelRestartRequired" || + ename === "DeadKernelError" || + (ename === "PythonRunnerError" && evalue.includes("kernel")) + ) { + state.alive = false + if (states.get(state.filePath) === state) forgetState(state.filePath) + } return } handler.resolve(m as unknown as RunResponse) } - // Byte-limited NDJSON reader: do not let readline buffer an unbounded - // single response line before the size check. - // Chunk list avoids re-copying a growing 48 MB line on every read. let pending: Buffer[] = [] let pendingBytes = 0 const decoder = new StringDecoder("utf8") @@ -390,8 +477,13 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap state.pending.clear() try { proc.kill("SIGKILL") - } catch { - // already gone + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ESRCH") { + record( + state, + warningFrom("cleanup", error, "killing the kernel after its stdout overflowed") + ) + } } return } @@ -421,13 +513,6 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap proc.on("close", (code, signal) => { state.alive = false - // When the kernel exits cleanly (exit 0), there is no failure to - // propagate for the shutdown request we sent ourselves; resolve it - // immediately so we don't wait for its 2s safety-net timer to fire. - // For non-zero or null exit codes, fall back to the standard failure - // path. Any other pending request (a real `cell`/`all` call in flight - // when the process died) must be failed explicitly so the caller sees - // "kernel exited unexpectedly" instead of a bogus `null` response. if (code === 0) { if (!state.readyResolved) { state.readyResolved = true @@ -453,21 +538,24 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap ) } state.pending.clear() - killProcessTree(proc, "SIGKILL", state.kernelPid) + killProcessTree(proc, "SIGKILL", state.kernelPid, killFailure(state)) + if (states.get(state.filePath) === state) forgetState(state.filePath) return } - killProcessTree(proc, "SIGKILL", state.kernelPid) + killProcessTree(proc, "SIGKILL", state.kernelPid, killFailure(state)) failAllPending( state, "kernel subprocess exited", `code=${code ?? "?"} signal=${signal ?? "none"}` ) + if (states.get(state.filePath) === state) forgetState(state.filePath) }) proc.on("error", (err) => { state.alive = false - killProcessTree(proc, "SIGKILL", state.kernelPid) + killProcessTree(proc, "SIGKILL", state.kernelPid, killFailure(state)) failAllPending(state, "kernel subprocess error", err.message) + if (states.get(state.filePath) === state) forgetState(state.filePath) }) return state @@ -507,10 +595,17 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap request: RunRequest, runtimeInput?: KernelRuntimeOptions ): Promise => { - const key = await canonicalPath(filePath) - return withKernelLock(key, () => - getOrStartUnlocked(key, request, runtimeFromRequest(runtimeInput)) - ) + const key = await canonicalPathForKernel(filePath) + return withKernelLock(key, async () => { + const state = await getOrStartUnlocked(key, request, runtimeFromRequest(runtimeInput)) + // The state is keyed by the canonical path, but the kernel list must + // report the spelling the caller actually used: on macOS the session + // dir is a symlink (/tmp -> /private/tmp) and on Windows an 8.3 short + // name (RUNNER~1), and a canonical listing would show paths the user + // never typed. + state.reportedPath = filePath + return state + }) } const getOrStartUnlocked = async ( @@ -532,7 +627,7 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap await killKernelUnlocked(filePath) } if (existing && !existing.alive) { - states.delete(filePath) + forgetState(filePath) } const state = spawnKernel(filePath, runtime, request.kernel) states.set(filePath, state) @@ -544,6 +639,7 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap new Promise((resolve) => { const id = state.nextId++ state.shutdownRequestId = id + const shutdownNonce = randomUUID() const timer = setTimeout(() => { state.pending.delete(id) handlerCleanup?.() @@ -554,6 +650,7 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap }, 2_000) let handlerCleanup: (() => void) | undefined state.pending.set(id, { + nonce: shutdownNonce, resolve: () => { clearTimeout(timer) handlerCleanup?.() @@ -573,11 +670,6 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap timer, cleanup: () => handlerCleanup?.() }) - // Guard against a closed/destroyed stdin before writing. The - // ``stdin?.write`` form silently no-ops on a missing stream but - // emits EPIPE asynchronously when the stream is destroyed; that - // becomes an uncaught error and crashes the plugin. Reject the - // shutdown request immediately so killKernel can move on. const stdin = state.proc.stdin if (!stdin || !stdin.writable) { clearTimeout(timer) @@ -588,8 +680,6 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap resolve() return } - // Attach a one-shot error handler so EPIPE / write-after-close - // failures are swallowed instead of crashing the process. const onStdinError = (): void => { clearTimeout(timer) handlerCleanup?.() @@ -614,25 +704,55 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap } }) - const canonicalPath = (filePath: string): Promise => - fsp.realpath(filePath).catch(() => filePath) + const canonicalPathForKernel = async ( + filePath: string + ): Promise => { + let canonical: string + let resolved = false + try { + canonical = await fsp.realpath(filePath) + resolved = true + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + const key = `path|${filePath}|${code ?? "EIO"}` + if (code !== "ENOENT" && !reported.has(key)) { + reported.add(key) + currentSink()?.add(warningFrom("path-resolution", error, `kernel key for ${filePath}`)) + } + canonical = filePath + } + if (resolved) { + canonicalAliases.set(filePath, canonical) + canonicalAliases.set(canonical, canonical) + } + return canonical + } const killKernel = async (inputPath: string): Promise => { - const filePath = await canonicalPath(inputPath) + const recorded = canonicalAliases.get(inputPath) + const canonical = await canonicalPathForKernel(inputPath) + const filePath = + !states.has(canonical) && recorded !== undefined && states.has(recorded) + ? recorded + : canonical return withKernelLock(filePath, () => killKernelUnlocked(filePath)) } const killKernelUnlocked = async (filePath: string): Promise => { const state = states.get(filePath) - if (!state) return - states.delete(filePath) + if (!state) { + forgetState(filePath) + return + } + forgetState(filePath) if (!state.alive) return await sendShutdown(state) if (state.alive) { - killProcessTree(state.proc, "SIGTERM", state.kernelPid) + killProcessTree(state.proc, "SIGTERM", state.kernelPid, killFailure(state)) await new Promise((resolve) => { const t = setTimeout(() => { - if (state.alive) killProcessTree(state.proc, "SIGKILL", state.kernelPid) + if (state.alive) + killProcessTree(state.proc, "SIGKILL", state.kernelPid, killFailure(state)) resolve() }, 3_000) state.proc.once("close", () => { @@ -647,15 +767,18 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap filePath: string, request: RunRequest, runtime?: KernelRuntimeOptions, - options?: { readonly signal?: AbortSignal } + options?: { + readonly signal?: AbortSignal + readonly warningSink?: WarningSink + } ) { - const kernelPath = yield* Effect.promise(() => canonicalPath(filePath)) if (options?.signal?.aborted) { return yield* new PythonRunnerError({ message: "warm kernel request aborted", - detail: `filePath=${kernelPath}` + detail: `filePath=${filePath}` }) } + const kernelPath = yield* Effect.promise(() => canonicalPathForKernel(filePath)) const state = yield* Effect.tryPromise({ try: () => getOrStart(kernelPath, request, runtime), catch: (err) => @@ -664,7 +787,20 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap detail: err instanceof Error ? err.message : String(err) }) }) + // execute canonicalizes before getOrStart, so getOrStart records the + // canonical spelling; the kernel list must report the one the caller + // used, which differs from the canonical form on macOS (symlinked temp + // dirs) and Windows (8.3 short names). + state.reportedPath = filePath + const requestSink = options?.warningSink const timeoutMs = request.timeoutMs ?? opts.defaultTimeoutMs + state.inflight += 1 + let readyInflight = true + const releaseReady = (): void => { + if (!readyInflight) return + readyInflight = false + state.inflight = Math.max(0, state.inflight - 1) + } yield* Effect.tryPromise({ try: () => withTimeout( @@ -672,7 +808,7 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap timeoutMs, "warm kernel did not become ready before the timeout", options?.signal, - () => void killKernel(kernelPath) + () => stopKernelIfIdle(kernelPath, state) ), catch: (err) => err instanceof PythonRunnerError @@ -681,50 +817,64 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap message: "warm kernel failed to become ready", detail: err instanceof Error ? err.message : String(err) }) - }) + }).pipe(Effect.ensuring(Effect.sync(releaseReady))) + state.inflight += 1 + const releaseInflight = (): void => { + state.inflight = Math.max(0, state.inflight - 1) + } const id = state.nextId++ + const nonce = randomUUID() const raw = yield* Effect.tryPromise({ try: () => new Promise((resolve, reject) => { - // Give the helper's own cell timeout a grace window first. If the - // JS timer still fires, stop the kernel so a timed-out cell does - // not keep running and block the next request. - const timer = setTimeout(() => { - const handler = state.pending.get(id) - handler?.cleanup?.() - state.pending.delete(id) - void killKernel(kernelPath) - reject( - new PythonRunnerError({ - message: `warm kernel request timed out after ${timeoutMs}ms`, - detail: `filePath=${kernelPath} id=${id}` - }) - ) - }, timeoutMs + 5_000) + let timer: NodeJS.Timeout | undefined + const armTimer = (): void => { + if (timer !== undefined) return + timer = setTimeout(() => { + const handler = state.pending.get(id) + handler?.cleanup?.() + state.pending.delete(id) + stopKernelIfIdle(kernelPath, state) + reject( + new PythonRunnerError({ + message: `warm kernel request timed out after ${timeoutMs}ms`, + detail: `filePath=${kernelPath} id=${id}` + }) + ) + }, 2 * timeoutMs + 5_000) + timer.unref?.() + } let cleanupStdinError: (() => void) | undefined let cleanupAbort: (() => void) | undefined state.pending.set(id, { resolve: (r) => { cleanupStdinError?.() cleanupAbort?.() + releaseInflight() resolve(r) }, reject: (e) => { cleanupStdinError?.() cleanupAbort?.() + releaseInflight() reject(e) }, timer, cleanup: () => { cleanupStdinError?.() cleanupAbort?.() - } + releaseInflight() + }, + ...(requestSink === undefined ? {} : { sink: requestSink }), + nonce }) const onAbort = () => { - clearTimeout(timer) + if (timer !== undefined) clearTimeout(timer) state.pending.delete(id) cleanupAbort?.() - void killKernel(kernelPath) + cleanupStdinError?.() + releaseInflight() + stopKernelIfIdle(kernelPath, state) reject( new PythonRunnerError({ message: "warm kernel request aborted", @@ -740,11 +890,8 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap cleanupAbort = () => options?.signal?.removeEventListener("abort", onAbort) try { - const payload = JSON.stringify({ id, ...request }) + "\n" - // Guard against a closed stdin before writing. If the kernel - // has already exited, the ``?.write`` form would silently - // no-op and the request would sit in ``pending`` until the - // timeout fired. Reject immediately with a clear cause. + const payload = + JSON.stringify({ ...request, filePath: kernelPath, id, nonce }) + "\n" const stdin = state.proc.stdin if (!stdin || !stdin.writable) { state.pending.delete(id) @@ -757,11 +904,9 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap ) return } - // One-shot error handler so a destroy-during-write (EPIPE) - // is observed on the request and not as an uncaught - // stream error that crashes the plugin. const onStdinError = (): void => { cleanupStdinError?.() + cleanupAbort?.() state.pending.delete(id) clearTimeout(timer) reject( @@ -773,10 +918,7 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap } stdin.once("error", onStdinError) cleanupStdinError = () => stdin.off("error", onStdinError) - // ``write`` returns false when the internal buffer is full; - // that is normal back-pressure, not an error. The data is - // queued and Node will flush it. We only reject on a real - // exception. + armTimer() stdin.write(payload) } catch (err) { cleanupStdinError?.() @@ -831,10 +973,26 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap }) const isRunning = (filePath: string): boolean => { + // States are keyed by canonicalPathForKernel, and its resolver and the + // sync one below disagree on Windows 8.3 spellings (RUNNER~1 vs the long + // name), so a fresh resolution can miss a kernel that is alive and well. + // Consult the alias recorded at registration first — the same spelling the + // state was stored under — and fall back to a fresh resolution only for + // paths that were never executed through this manager. + const aliased = canonicalAliases.get(filePath) + if (aliased !== undefined) { + const known = states.get(aliased) + if (known !== undefined) return known.alive + } const key = (() => { try { return realpathSync(filePath) - } catch { + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + currentSink()?.add( + warningFrom("path-resolution", error, `kernel lookup for ${filePath}`) + ) + } return filePath } })() @@ -844,14 +1002,18 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap const list = (): ReadonlyArray => { const out: KernelInfo[] = [] - for (const [filePath, state] of states) { + for (const state of states.values()) { if (!state.alive) continue out.push({ - filePath, + // The spelling the caller last used, not the canonical key: the list + // is user-facing and canonical paths differ from what was typed on + // every platform that resolves symlinks or 8.3 short names. + filePath: state.reportedPath, pid: state.pid, lastUsedAt: state.lastUsed, requestsHandled: state.requestsHandled, - stderrTail: state.stderrTail.slice(-STDERR_TAIL_MAX).join("\n") + stderrTail: state.stderrTail.slice(-STDERR_TAIL_MAX).join("\n"), + warnings: [...state.warnings] }) } return out @@ -872,6 +1034,7 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap const all = Array.from(states.keys()) await Promise.all(all.map((k) => killKernel(k))) states.clear() + canonicalAliases.clear() }) const stats = (): KernelManagerStats => { @@ -889,7 +1052,10 @@ export const makeKernelManager = (opts: KernelManagerOptions): KernelManagerShap restart, shutdown, disposeAll, - stats + stats, + setWarningSink: (next) => { + sinkTarget.sink = next + } } } @@ -898,7 +1064,10 @@ export interface KernelManagerShape { filePath: string, request: RunRequest, runtime?: KernelRuntimeOptions, - options?: { readonly signal?: AbortSignal } + options?: { + readonly signal?: AbortSignal + readonly warningSink?: WarningSink + } ) => Effect.Effect readonly isRunning: (filePath: string) => boolean readonly list: () => ReadonlyArray @@ -906,4 +1075,5 @@ export interface KernelManagerShape { readonly shutdown: (filePath: string) => Effect.Effect readonly disposeAll: () => Effect.Effect readonly stats: () => KernelManagerStats + readonly setWarningSink?: (sink: WarningSink | undefined) => void } diff --git a/src/services/NotebookCleanService.ts b/src/services/NotebookCleanService.ts index 3673ed1..e6dea23 100644 --- a/src/services/NotebookCleanService.ts +++ b/src/services/NotebookCleanService.ts @@ -15,6 +15,7 @@ import { } from "./PermissionService.js" import type { CellRaw, CodeCellRaw } from "../domain/cell.js" import type { NotebookRaw } from "../domain/notebook.js" +import type { PatchFailureReason, WriteMode } from "../utils/json.js" export interface CleanOptions { readonly clearOutputs: boolean @@ -33,7 +34,10 @@ export interface CleanResult { readonly removedExecutionCounts: number readonly removedWidgets: number readonly removedImages: number + readonly normalizedSources: number readonly notebook: NotebookRaw + readonly writeMode: WriteMode | undefined + readonly writeModeReason?: PatchFailureReason | undefined } export interface NotebookCleanServiceShape { @@ -131,11 +135,13 @@ const makeCleanImpl = ( let removedExec = 0 let removedWidgets = 0 let removedImages = 0 + let normalizedSources = 0 const cells = notebook.cells.map((cell) => { const normalized = opts.normalizeSource ? normalizeCellSource(cell) : { cell, changed: false } + if (normalized.changed) normalizedSources += 1 if (normalized.cell.cell_type !== "code") { let touched = normalized.changed let nextCell = normalized.cell @@ -231,7 +237,9 @@ const makeCleanImpl = ( removedExecutionCounts: 0, removedWidgets: 0, removedImages: 0, - notebook + normalizedSources: 0, + notebook, + writeMode: undefined } } @@ -252,13 +260,17 @@ const makeCleanImpl = ( removedExecutionCounts: removedExec, removedWidgets, removedImages, + normalizedSources, options: opts } }) yield* assertRevisionUnchanged(fileSvc, pinned, revision) - yield* fileSvc.writeAtomic(pinned, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(pinned, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) return { @@ -269,7 +281,10 @@ const makeCleanImpl = ( removedExecutionCounts: removedExec, removedWidgets, removedImages, - notebook: newNotebook + normalizedSources, + notebook: newNotebook, + writeMode: write.mode, + writeModeReason: write.reason } }) ) diff --git a/src/services/NotebookEditService.ts b/src/services/NotebookEditService.ts index 814a6ae..220f0d6 100644 --- a/src/services/NotebookEditService.ts +++ b/src/services/NotebookEditService.ts @@ -8,15 +8,16 @@ import { PathOutsideWorktreeError, PermissionDeniedError } from "../domain/errors.js" -import type { NotebookFileServiceShape } from "./NotebookFileService.js" +import type { NotebookFileServiceShape, WriteMode } from "./NotebookFileService.js" +import type { PatchFailureReason } from "../utils/json.js" import { assertRevisionUnchanged, contentHash, pinRealPath } from "./revision.js" import { randomUUID } from "node:crypto" import type { PathServiceShape } from "./PathService.js" import { type PermissionServiceShape } from "./PermissionService.js" -import { cellSource, type NotebookRaw } from "../domain/notebook.js" -import type { CellRaw, CodeCellRaw, MarkdownCellRaw, RawCellRaw } from "../domain/cell.js" +import { cellSource, formatSourceLike, type NotebookRaw } from "../domain/notebook.js" +import type { CellRaw, CodeCellRaw, MarkdownCellRaw, RawCellRaw, Source } from "../domain/cell.js" import { firstLine, truncatePreview } from "../utils/truncate.js" export interface EditRequest { @@ -33,6 +34,8 @@ export interface EditResult { readonly clearedOutputs: boolean readonly changed: boolean readonly notebook: NotebookRaw + readonly writeMode: WriteMode | undefined + readonly writeModeReason?: PatchFailureReason | undefined } export interface InsertResult { @@ -42,6 +45,8 @@ export interface InsertResult { readonly cellType: "code" | "markdown" | "raw" readonly totalCells: number readonly preview: string + readonly writeMode: WriteMode + readonly writeModeReason?: PatchFailureReason | undefined } export interface DeleteResult { @@ -51,6 +56,8 @@ export interface DeleteResult { readonly deletedType: "code" | "markdown" | "raw" readonly deletedPreview: string readonly totalCells: number + readonly writeMode: WriteMode + readonly writeModeReason?: PatchFailureReason | undefined } export interface MoveResult { @@ -60,6 +67,8 @@ export interface MoveResult { readonly toIndex: number readonly cellType: CellType readonly totalCells: number + readonly writeMode: WriteMode | undefined + readonly writeModeReason?: PatchFailureReason | undefined } export type CellType = "code" | "markdown" | "raw" @@ -138,18 +147,20 @@ export interface NotebookEditServiceShape { const buildNewCell = ( cellType: CellType, source: string, - nbformatMinor: number + nbformatMinor: number, + previousSource: Source | undefined ): CellRaw => { - // nbformat 4.5 requires every cell to carry a stable id. const id = nbformatMinor >= 5 ? { id: randomUUID() } : {} + const shaped = + previousSource === undefined ? source : formatSourceLike(previousSource, source) if (cellType === "code") { const cell: CodeCellRaw = { cell_type: "code", + execution_count: null, ...id, metadata: {}, - execution_count: null, - source, - outputs: [] + outputs: [], + source: shaped } return cell } @@ -158,7 +169,7 @@ const buildNewCell = ( cell_type: "markdown", ...id, metadata: {}, - source + source: shaped } return cell } @@ -166,7 +177,7 @@ const buildNewCell = ( cell_type: "raw", ...id, metadata: {}, - source + source: shaped } return cell } @@ -213,6 +224,7 @@ const makeEditImpl = ( const cell = notebook.cells[idx] as CellRaw const oldSource = cellSource(cell) const newSource = request.source + const newCellSource = formatSourceLike(cell.source, newSource) const displayPath = pathSvc.toDisplay(abs) const mode = request.clearOutputs ?? "auto" const sourceChanged = oldSource !== newSource @@ -230,7 +242,8 @@ const makeEditImpl = ( cellType: cell.cell_type, clearedOutputs: false, changed: false, - notebook + notebook, + writeMode: undefined } } @@ -257,19 +270,19 @@ const makeEditImpl = ( if (clearedOutputs) { return { ...code, - source: newSource, + source: newCellSource, outputs: [], execution_count: null } } - return { ...code, source: newSource } + return { ...code, source: newCellSource } } if (cell.cell_type === "markdown") { const md = cell as MarkdownCellRaw - return { ...md, source: newSource } + return { ...md, source: newCellSource } } const raw = cell as RawCellRaw - return { ...raw, source: newSource } + return { ...raw, source: newCellSource } })() const cells = notebook.cells.slice() @@ -277,8 +290,11 @@ const makeEditImpl = ( const newNotebook: NotebookRaw = { ...notebook, cells } yield* assertRevisionUnchanged(fileSvc, pinned, revision) - yield* fileSvc.writeAtomic(pinned, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(pinned, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) return { @@ -288,7 +304,9 @@ const makeEditImpl = ( cellType: cell.cell_type, clearedOutputs, changed: true, - notebook: newNotebook + notebook: newNotebook, + writeMode: write.mode, + writeModeReason: write.reason } }) ) @@ -333,10 +351,12 @@ const makeEditImpl = ( } const targetIdx = index === undefined || index >= total ? total : index + const template = notebook.cells[0] as CellRaw | undefined const newCell = buildNewCell( cellType, source, - notebook.nbformat_minor ?? 0 + notebook.nbformat_minor ?? 0, + template?.source ) const preview = firstLine(source).slice(0, 200) @@ -365,8 +385,11 @@ const makeEditImpl = ( const newNotebook: NotebookRaw = { ...notebook, cells } yield* assertRevisionUnchanged(fileSvc, pinned, revision) - yield* fileSvc.writeAtomic(pinned, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(pinned, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) const displayPath = pathSvc.toDisplay(abs) @@ -376,7 +399,9 @@ const makeEditImpl = ( cellIndex: targetIdx, cellType, totalCells: total + 1, - preview + preview, + writeMode: write.mode, + writeModeReason: write.reason } }) ) @@ -446,8 +471,11 @@ const makeEditImpl = ( const newNotebook: NotebookRaw = { ...notebook, cells } yield* assertRevisionUnchanged(fileSvc, pinned, revision) - yield* fileSvc.writeAtomic(pinned, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(pinned, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) const displayPath = pathSvc.toDisplay(abs) @@ -457,7 +485,9 @@ const makeEditImpl = ( deletedIndex: cellIndex, deletedType: cellType, deletedPreview, - totalCells: total - 1 + totalCells: total - 1, + writeMode: write.mode, + writeModeReason: write.reason } }) ) @@ -521,7 +551,8 @@ const makeEditImpl = ( fromIndex, toIndex: clampedTo, cellType, - totalCells: total + totalCells: total, + writeMode: undefined } } @@ -550,8 +581,11 @@ const makeEditImpl = ( const newNotebook: NotebookRaw = { ...notebook, cells } yield* assertRevisionUnchanged(fileSvc, pinned, revision) - yield* fileSvc.writeAtomic(pinned, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(pinned, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) return { @@ -560,7 +594,9 @@ const makeEditImpl = ( fromIndex, toIndex: clampedTo, cellType, - totalCells: total + totalCells: total, + writeMode: write.mode, + writeModeReason: write.reason } }) ) diff --git a/src/services/NotebookExecutionService.ts b/src/services/NotebookExecutionService.ts index dc88493..802a554 100644 --- a/src/services/NotebookExecutionService.ts +++ b/src/services/NotebookExecutionService.ts @@ -13,6 +13,7 @@ import { } from "../domain/errors.js" import type { NotebookFileServiceShape } from "./NotebookFileService.js" import type { PathServiceShape } from "./PathService.js" +import type { PatchFailureReason, WriteMode } from "../utils/json.js" import { type PermissionServiceShape } from "./PermissionService.js" @@ -36,7 +37,13 @@ import { MAX_RUN_RESPONSE_CHARS } from "../utils/limits.js" import { formatHint, type TruncationHintKey } from "../utils/i18n.js" -import type { NotebookRaw } from "../domain/notebook.js" +import { splitSourceLines, type NotebookRaw } from "../domain/notebook.js" +import { + type Warning, + type WarningSink, + makeWarningSink, + warningFrom +} from "../utils/warnings.js" export type ExecutionMode = "cell" | "range" | "all" | "from" @@ -60,13 +67,19 @@ export interface ExecutionResult { readonly durationMs: number readonly saved: boolean readonly response: RunResponse + readonly warnings?: ReadonlyArray + readonly writeMode?: WriteMode | undefined + readonly writeModeReason?: PatchFailureReason | undefined } export interface NotebookExecutionServiceShape { readonly execute: ( filePath: string, request: ExecutionRequest, - options?: { readonly signal?: AbortSignal } + options?: { + readonly signal?: AbortSignal + readonly warningSink?: WarningSink + } ) => Effect.Effect readonly reportEnv: ( filePath: string, @@ -77,16 +90,16 @@ export interface NotebookExecutionServiceShape { export interface ReportEnvOptions { readonly timeoutMs?: number | undefined readonly signal?: AbortSignal | undefined - /** The caller already asserted shell for the probe and helper. */ readonly skipShellPermission?: boolean | undefined + readonly warningSink?: WarningSink | undefined } export interface ExecutionOptions { readonly kernelManager?: KernelManagerShape | undefined readonly warmKernel: boolean readonly defaultTimeoutMs: number - /** Configured interpreter, used for the pre-probe shell permission. */ readonly pythonPath?: string | undefined + readonly warningSink?: WarningSink | undefined } const runPython = ( @@ -95,7 +108,8 @@ const runPython = ( payload: RunRequest, workingDirectory: string | undefined, timeoutMs: number, - externalSignal?: AbortSignal + externalSignal?: AbortSignal, + warningSink?: WarningSink ): Effect.Effect => Effect.gen(function* () { const result = yield* Effect.tryPromise({ @@ -111,14 +125,13 @@ const runPython = ( detached: process.platform !== "win32" } ) - // Swallow EPIPE from a helper that exits before reading stdin. child.stdin.on("error", () => {}) const stdoutChunks: Buffer[] = [] const stderrChunks: Buffer[] = [] let stdoutBytes = 0 let stderrBytes = 0 let forceTimer: NodeJS.Timeout | undefined - const signalTree = (signal: NodeJS.Signals) => { + const signalTree = (signal: NodeJS.Signals, notify?: (error: unknown) => void) => { if (child.pid === undefined) return if (process.platform === "win32") { killWindowsTree(child.pid) @@ -128,17 +141,22 @@ const runPython = ( } catch { try { child.kill(signal) - } catch { - // already gone + } catch (directError) { + if ((directError as NodeJS.ErrnoException).code !== "ESRCH") { + notify?.(directError) + } } } } } + const notifyKill = (error: unknown): void => { + warningSink?.add( + warningFrom("cleanup", error, "killing the python runner after a timeout or abort") + ) + } const killTree = () => { - // Give the Python helper a chance to kill the Jupyter kernel's - // process group (it runs in its own session), then force it. - signalTree("SIGTERM") - forceTimer = setTimeout(() => signalTree("SIGKILL"), 750) + signalTree("SIGTERM", notifyKill) + forceTimer = setTimeout(() => signalTree("SIGKILL", notifyKill), 750) forceTimer.unref?.() } let timer: NodeJS.Timeout | undefined @@ -180,7 +198,6 @@ const runPython = ( stdoutChunks.push(chunk) }) child.stderr.on("data", (chunk: Buffer) => { - // stderr is diagnostic only: keep the tail bounded. if (stderrBytes >= 1024 * 1024) return stderrBytes += chunk.length stderrChunks.push(chunk) @@ -192,6 +209,9 @@ const runPython = ( }) child.on("close", (code) => { clearTimeout(timer) + if (forceTimer !== undefined) { + signalTree("SIGKILL", notifyKill) + } cleanup() const stdout = Buffer.concat(stdoutChunks).toString("utf8") const stderr = Buffer.concat(stderrChunks).toString("utf8") @@ -242,8 +262,6 @@ const runPython = ( }) } if (!parsed.data.success && parsed.data.error) { - // Honor maxOutputChars even on the failure path; the helper caps at - // 8k but callers may ask for much less. const cap = Math.max(0, payload.maxOutputChars ?? 6_000) const ename = parsed.data.error.ename.slice(0, cap) const evalue = parsed.data.error.evalue.slice( @@ -306,7 +324,6 @@ const truncateCellSummary = ( summary: CellExecutionSummary, maxOutputChars: number ): CellExecutionSummary => { - // One budget for the whole cell: stdout + stderr + result + tracebacks. let remaining = Math.max(0, maxOutputChars) const take = (text: string | undefined): string | undefined => { const value = truncateText(text, remaining, undefined, "output") @@ -357,23 +374,29 @@ const truncateRunResponse = ( response: RunResponse, maxOutputChars: number ): RunResponse => { - // Per-cell budget plus a hard per-response budget so a 500-cell notebook - // cannot return megabytes of stdout in one tool result. - let remaining = Math.min( + const summaries = response.outputs.slice(0, 1_000) + const perSummaryReserve = 200 + const totalBudget = Math.min( MAX_RUN_RESPONSE_CHARS, - Math.max(0, maxOutputChars) * Math.max(1, response.outputs.length) + Math.max(0, maxOutputChars) * Math.max(1, summaries.length) ) - const outputs = response.outputs.slice(0, 1_000).map((o) => { - const budget = Math.min(maxOutputChars, remaining) - const truncated = truncateCellSummary(o, budget) - // Account for the status line and structural JSON overhead. - remaining = Math.max( - 0, - remaining - cellSummaryChars(truncated) - 200 + const available = Math.max( + summaries.length, + totalBudget - perSummaryReserve * summaries.length + ) + const fairShare = Math.max(1, Math.floor(available / Math.max(1, summaries.length))) + let remaining = available + const outputs = summaries.map((summary, index) => { + const cellsLeft = Math.max(1, summaries.length - index) + const share = Math.max(1, Math.floor(remaining / cellsLeft)) + const truncated = truncateCellSummary( + summary, + Math.max(1, Math.min(fairShare, share)) ) + remaining = Math.max(0, remaining - cellSummaryChars(truncated)) return truncated }) - let errorBudget = Math.min(maxOutputChars, remaining) + let errorBudget = Math.min(maxOutputChars, Math.max(0, remaining)) let error: RunResponse["error"] | undefined if (response.error !== undefined) { const ename = truncateText(response.error.ename, errorBudget) ?? "Error" @@ -399,12 +422,128 @@ const truncateRunResponse = ( } } +const SPLIT_TEXT_MIMES = new Set([ + "application/javascript", + "image/svg+xml" +]) + +const isSplittableMime = (key: string): boolean => + key.startsWith("text/") || SPLIT_TEXT_MIMES.has(key) + +export type TextShape = "arrays" | "strings" + +const shapeOfValue = (value: unknown): TextShape | undefined => { + if (typeof value === "string") return "strings" + if (Array.isArray(value)) return "arrays" + return undefined +} + +export const textShapeOfCell = (cell: CellRaw, fallback: TextShape): TextShape => { + const evidences: TextShape[] = [] + if (cell.cell_type === "code") { + for (const output of (cell as CodeCellRaw).outputs) { + const text = shapeOfValue(output["text"]) + if (text !== undefined) evidences.push(text) + const data = output["data"] + if (data !== null && typeof data === "object" && !Array.isArray(data)) { + for (const [key, value] of Object.entries(data as Record)) { + if (!isSplittableMime(key)) continue + const shape = shapeOfValue(value) + if (shape !== undefined) evidences.push(shape) + } + } + } + } + if (evidences.length > 0) { + const arrays = evidences.filter((shape) => shape === "arrays").length + return arrays * 2 >= evidences.length ? "arrays" : "strings" + } + if (Array.isArray(cell.source)) return "arrays" + if (typeof cell.source === "string") return "strings" + return fallback +} + +export interface OutputTextShapes { + readonly text: TextShape | undefined + readonly data: ReadonlyMap +} + +export type CellValueShapes = ReadonlyArray + +export const captureValueShapes = (cell: CellRaw): CellValueShapes => { + if (cell.cell_type !== "code") return [] + return (cell as CodeCellRaw).outputs.map((output) => { + const data = new Map() + const bundle = output["data"] + if (bundle !== null && typeof bundle === "object" && !Array.isArray(bundle)) { + for (const [key, value] of Object.entries(bundle as Record)) { + if (!isSplittableMime(key)) continue + const shape = shapeOfValue(value) + if (shape !== undefined) data.set(key, shape) + } + } + return { text: shapeOfValue(output["text"]), data } + }) +} + +const restoreDataShapes = ( + output: Record, + previous: OutputTextShapes | undefined, + cellShape: TextShape +): Record => { + const outputType = output["output_type"] + if (outputType !== "execute_result" && outputType !== "display_data") return output + const data = output["data"] + if (data === null || typeof data !== "object" || Array.isArray(data)) return output + let next: Record | undefined + for (const [key, value] of Object.entries(data as Record)) { + if (!isSplittableMime(key) || typeof value !== "string") continue + if ((previous?.data.get(key) ?? cellShape) !== "arrays") continue + if (next === undefined) next = { ...(data as Record) } + next[key] = splitSourceLines(value) + } + if (next === undefined) return output + return { ...output, data: next } +} + +export const restoreValueShapes = ( + outputs: ReadonlyArray>, + previous: CellValueShapes | undefined, + cellShape: TextShape +): Array> => + outputs.map((output, index) => { + const prior = previous?.[index] + if (typeof output["text"] === "string" && (prior?.text ?? cellShape) === "arrays") { + return restoreDataShapes( + { ...output, text: splitSourceLines(output["text"] as string) }, + prior, + cellShape + ) + } + return restoreDataShapes(output, prior, cellShape) + }) + +export const notebookTextShape = (notebook: NotebookRaw): TextShape => { + const shapes = notebook.cells.map((cell) => textShapeOfCell(cell as CellRaw, "strings")) + const arrays = shapes.filter((shape) => shape === "arrays").length + return arrays * 2 >= shapes.length ? "arrays" : "strings" +} + +export const notebookUsesLineArrays = (notebook: NotebookRaw): boolean => + notebookTextShape(notebook) === "arrays" + export const buildPersistedOutputs = ( summary: CellExecutionSummary ): Array> => { - // Output order is intentional: stdout, stderr (stream), then the textual - // result, then any rich displays, then errors. Jupyter Lab renders them in - // this order, so we keep it stable across re-executions. + if (summary.rawOutputs !== undefined && summary.rawOutputs.length > 0) { + const raw = summary.rawOutputs.filter( + (output) => + output !== null && + typeof output === "object" && + typeof (output as { output_type?: unknown }).output_type === "string" + ) + if (raw.length > 0) return raw.map((output) => ({ ...output })) + } const outputs: Array> = [] if (summary.stdout !== undefined) { outputs.push({ @@ -450,6 +589,57 @@ export const buildPersistedOutputs = ( return outputs } +export interface MergeShapeInputs { + readonly fallback: TextShape + readonly beforeShapes: ReadonlyMap | undefined + readonly beforeValueShapes: ReadonlyMap | undefined +} + +export const mergeExecutedOutputs = ( + filePath: string, + cells: ReadonlyArray, + executedCells: ReadonlyArray, + summaries: ReadonlyArray, + shapes: MergeShapeInputs +): Effect.Effect, CellIndexOutOfBoundsError> => + Effect.gen(function* () { + const summaryByIndex = new Map() + for (const summary of summaries) { + if (!summaryByIndex.has(summary.cellIndex)) { + summaryByIndex.set(summary.cellIndex, summary) + } + } + const merged = new Map() + for (const idx of executedCells) { + if (idx < 0 || idx >= cells.length) { + return yield* new CellIndexOutOfBoundsError({ + message: `runner reported executed cell ${idx} but notebook has ${cells.length} cells`, + filePath, + cellIndex: idx, + total: cells.length + }) + } + const cell = cells[idx] as CellRaw + if (cell.cell_type !== "code") continue + const summary = summaryByIndex.get(idx) + if (summary === undefined) continue + const next: CodeCellRaw = { + ...cell, + outputs: restoreValueShapes( + summary.rawOutputs ?? buildPersistedOutputs(summary), + shapes.beforeValueShapes?.get(idx), + shapes.beforeShapes?.get(idx) ?? shapes.fallback + ) as CodeCellRaw["outputs"], + execution_count: + summary.executionCount !== undefined && summary.executionCount !== null + ? summary.executionCount + : null + } + merged.set(idx, next) + } + return merged + }) + const makeExecutionImpl = ( pathSvc: PathServiceShape, fileSvc: NotebookFileServiceShape, @@ -460,22 +650,28 @@ const makeExecutionImpl = ( const kernelManager = execOpts?.kernelManager const warmKernel = execOpts?.warmKernel ?? false const defaultTimeoutMs = execOpts?.defaultTimeoutMs ?? 120_000 + const defaultSink = execOpts?.warningSink - // Only `all` and `cell` use the warm kernel; the one-shot helper handles - // `range` and `from` because those modes don't share state across cells in - // a way the warm kernel can reuse, and `env` is a one-shot probe. const useWarmKernel = (mode: ExecutionMode): boolean => warmKernel && kernelManager !== undefined && (mode === "all" || mode === "cell") return { execute: (filePath, request, options) => Effect.gen(function* () { + const sink = makeWarningSink() + const requestedSink = options?.warningSink ?? defaultSink + const record = (warning: Warning): void => { + sink.add(warning) + requestedSink?.add(warning) + } + const finish = (result: ExecutionResult): ExecutionResult => { + const warnings = sink.drain() + return warnings.length === 0 ? result : { ...result, warnings } + } const abs = yield* pathSvc.resolve(filePath) yield* pathSvc.ensureInsideWorktree(abs) yield* pathSvc.ensureExists(abs) const stat = yield* Effect.tryPromise({ - // stat follows symlinks: a link to a regular notebook is valid, a - // link to a FIFO/socket/device still reports non-regular. try: () => fsp.stat(abs), catch: (err) => new NotebookValidationError({ @@ -491,20 +687,18 @@ const makeExecutionImpl = ( issues: ["refusing to read a FIFO, socket, or device"] }) } - // Validate schema and the 50 MB limit even when save=false; the - // Python helper would otherwise load arbitrary JSON/large files. yield* fileSvc.read(abs) const displayPath = pathSvc.toDisplay(abs) - const kernelPath = yield* Effect.promise(() => - fsp.realpath(abs).catch(() => abs) - ) - // Pin the canonical target before any probe/helper work; the lexical - // path can be swapped to an outside symlink after the first check. + const kernelPath = yield* Effect.promise(async () => { + try { + return await fsp.realpath(abs) + } catch (error) { + record(warningFrom("path-resolution", error, `kernel path for ${abs}`)) + return abs + } + }) yield* pathSvc.ensureInsideWorktree(kernelPath) - // Validate the request before we touch Python: a malformed payload is a - // user error, not an environment error. This ordering also makes the - // service testable in environments without a Python runtime. const parsed = RunRequestSchema.safeParse({ filePath: abs, mode: request.mode, @@ -526,10 +720,6 @@ const makeExecutionImpl = ( ) }) } - // The helper must never write the notebook itself: the TypeScript - // side asks for `edit` permission and persists outputs atomically. - // Keep the full raw outputs available only when the caller asked to - // save, so small reads do not pay for base64 images. const kernelEnv = kernelEnvOverrides() const payload: RunRequest = { ...parsed.data, @@ -563,8 +753,6 @@ const makeExecutionImpl = ( }) } - // Include both the alias the caller used and the pinned real target: - // a deny on either identity must be evaluated. const lexicalAliases = yield* permSvc.aliases(abs) const kernelAliases = yield* permSvc.aliases(kernelPath) const absAliases = [...new Set([...lexicalAliases, ...kernelAliases])] @@ -613,7 +801,9 @@ const makeExecutionImpl = ( } }) - const probe = yield* pythonSvc.probe() + const probe = yield* pythonSvc.probe({ + warningSink: requestedSink + }) if (probe.from === "none") { return yield* new NotebookNotImplementedError({ message: @@ -648,9 +838,24 @@ const makeExecutionImpl = ( } let beforeHash: string | undefined + let beforeShapes: Map | undefined + let beforeValueShapes: Map | undefined if (request.save) { const before = yield* fileSvc.readWithText(kernelPath) beforeHash = createHash("sha256").update(before.text).digest("hex") + const fallback = notebookTextShape(before.notebook) + beforeShapes = new Map( + before.notebook.cells.map((cell, index) => [ + index, + textShapeOfCell(cell as CellRaw, fallback) + ]) + ) + beforeValueShapes = new Map( + before.notebook.cells.map((cell, index) => [ + index, + captureValueShapes(cell as CellRaw) + ]) + ) } const startTs = Date.now() @@ -659,7 +864,13 @@ const makeExecutionImpl = ( kernelPath, payload, { pythonPath: probe.pythonPath, helperPath }, - options + { + ...options, + warningSink: { + add: record, + drain: () => [] + } + } ) : yield* runPython( probe.pythonPath, @@ -667,12 +878,15 @@ const makeExecutionImpl = ( payload, workingDirectory, request.timeoutMs, - options?.signal + options?.signal, + requestedSink ) const durationMs = Date.now() - startTs const truncated = truncateRunResponse(response, request.maxOutputChars) let wrote = false + let writeMode: WriteMode | undefined + let writeModeReason: PatchFailureReason | undefined if (request.save) { if (response.outputs.some((output) => output.rawOutputsOmitted === true)) { return yield* new NotebookValidationError({ @@ -690,30 +904,18 @@ const makeExecutionImpl = ( const snapshot = yield* fileSvc.readWithText(kernelPath) const notebook = snapshot.notebook if (notebook.cells.length > 0) { - const cellsByIndex = new Map() - for (const idx of response.executedCells) { - if (idx < 0 || idx >= notebook.cells.length) { - return yield* new CellIndexOutOfBoundsError({ - message: `runner reported executed cell ${idx} but notebook has ${notebook.cells.length} cells`, - filePath: abs, - cellIndex: idx, - total: notebook.cells.length - }) - } - const cell = notebook.cells[idx] as CellRaw - if (cell.cell_type !== "code") continue - const summary = response.outputs.find((o) => o.cellIndex === idx) - if (!summary) continue - const next: CodeCellRaw = { - ...cell, - outputs: (summary.rawOutputs ?? buildPersistedOutputs(summary)) as CodeCellRaw["outputs"], - execution_count: - summary.executionCount !== undefined && summary.executionCount !== null - ? summary.executionCount - : null + const notebookShape = notebookTextShape(notebook) + const cellsByIndex = yield* mergeExecutedOutputs( + abs, + notebook.cells as ReadonlyArray, + response.executedCells, + response.outputs, + { + fallback: notebookShape, + beforeShapes, + beforeValueShapes } - cellsByIndex.set(idx, next) - } + ) if (cellsByIndex.size > 0) { if ( beforeHash !== undefined && @@ -731,25 +933,32 @@ const makeExecutionImpl = ( } const newCells = notebook.cells.map((c, i) => cellsByIndex.get(i) ?? c) const newNotebook: NotebookRaw = { ...notebook, cells: newCells } - yield* fileSvc.writeAtomic(kernelPath, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(kernelPath, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) wrote = true + writeMode = write.mode + writeModeReason = write.reason } } }) ) } - return { + return finish({ displayPath, absPath: abs, kernelPath, executedCells: response.executedCells.slice(0, 10_000), durationMs, saved: request.save && wrote, - response: truncated - } + response: truncated, + writeMode, + writeModeReason + }) }), reportEnv: (filePath, options) => Effect.gen(function* () { @@ -788,7 +997,8 @@ const makeExecutionImpl = ( }) } - const probe = yield* pythonSvc.probe() + const reportEnvSink = options?.warningSink ?? defaultSink + const probe = yield* pythonSvc.probe({ warningSink: reportEnvSink }) if (probe.from === "none") { return yield* new NotebookNotImplementedError({ message: @@ -810,9 +1020,6 @@ const makeExecutionImpl = ( metadata: { filePath: abs, pythonPath: probe.pythonPath } }) } - // The 30s floor is a minimum for env-mode (pip freeze + import probes); - // the configured defaultTimeoutMs is the upper bound when the caller - // does not pass an explicit value. const envTimeout = options?.timeoutMs ?? Math.max(30_000, defaultTimeoutMs) const envParsed = RunRequestSchema.safeParse({ filePath: abs, @@ -828,9 +1035,16 @@ const makeExecutionImpl = ( ) }) } - const envRealPath = yield* Effect.promise(() => - fsp.realpath(abs).catch(() => abs) - ) + const envRealPath = yield* Effect.promise(async () => { + try { + return await fsp.realpath(abs) + } catch (error) { + reportEnvSink?.add( + warningFrom("path-resolution", error, `env report path for ${abs}`) + ) + return abs + } + }) yield* pathSvc.ensureInsideWorktree(envRealPath) const payload: RunRequest = { ...envParsed.data, @@ -842,7 +1056,8 @@ const makeExecutionImpl = ( payload, undefined, envTimeout, - options?.signal + options?.signal, + reportEnvSink ) if (!response.env) { return yield* new PythonRunnerError({ diff --git a/src/services/NotebookExportService.ts b/src/services/NotebookExportService.ts index c332813..6d76b1d 100644 --- a/src/services/NotebookExportService.ts +++ b/src/services/NotebookExportService.ts @@ -259,8 +259,6 @@ const makeExportImpl = ( : code.outputs.filter((out) => detectOutputKind(out) === "error") const section = formatOutputs({ ...code, outputs }, { includeImages: false, - // File exports are meant to be complete; maxExportChars only - // caps the text returned to the model. maxOutputChars: Number.MAX_SAFE_INTEGER, maxTracebackChars: Number.MAX_SAFE_INTEGER }) @@ -302,7 +300,6 @@ const makeExportImpl = ( const outputReal = yield* Effect.promise(() => realTarget(outAbs)) const isNotebookName = (value: string): boolean => { let base = path.basename(value).toLowerCase() - // Windows strips trailing dots/spaces, so "n.ipynb " is "n.ipynb". if (process.platform === "win32") base = base.replace(/[ .]+$/, "") return base.endsWith(".ipynb") } @@ -319,8 +316,25 @@ const makeExportImpl = ( issues: ["refusing to write an export over a .ipynb file"] }) } - // Pin the resolved destination: a symlink swapped during the - // permission prompt must not redirect the write to a new target. + const extensionOf = (value: string): string => { + let base = path.basename(value).toLowerCase() + if (process.platform === "win32") base = base.replace(/[ .]+$/, "") + const dot = base.lastIndexOf(".") + return dot <= 0 ? "" : base.slice(dot) + } + const exportExtensions = new Set([".md", ".markdown", ".py", ".txt", ".rst"]) + const outputExtension = extensionOf(outputReal) + if (!exportExtensions.has(outputExtension)) { + return yield* new NotebookValidationError({ + message: + "outputPath must use an export extension (.md, .markdown, .py, .txt, .rst)", + filePath: abs, + issues: [ + `refusing to write an export to "${path.basename(outputReal)}"`, + "pass --outputPath with a markdown, python, or text extension" + ] + }) + } const writeTarget = outputReal const lexicalPaths = yield* permSvc.aliases(outAbs) const pinnedPaths = yield* permSvc.aliases(writeTarget) @@ -340,7 +354,6 @@ const makeExportImpl = ( length: rendered.length } }) - // The tool output is capped, but a file export must be complete. yield* pathSvc.writeFileSafe(writeTarget, rendered, { noFollowFinal: true }) diff --git a/src/services/NotebookFileService.ts b/src/services/NotebookFileService.ts index 2966dbe..89a36a4 100644 --- a/src/services/NotebookFileService.ts +++ b/src/services/NotebookFileService.ts @@ -1,7 +1,7 @@ import { Effect, Semaphore } from "effect" import { randomUUID } from "node:crypto" import * as fsp from "node:fs/promises" -import { constants as fsConstants } from "node:fs" +import { constants as fsConstants, type Stats } from "node:fs" import * as path from "node:path" import { NotebookNotFoundError, @@ -10,26 +10,130 @@ import { NotebookWriteError, PathOutsideWorktreeError } from "../domain/errors.js" -import { NotebookSchema, type NotebookRaw } from "../domain/notebook.js" -import { safeParseJson, stringifyNotebook } from "../utils/json.js" +import { NotebookSchema, applyNotebookDefaults, type NotebookRaw } from "../domain/notebook.js" +import { MAX_JSON_DEPTH, type PatchFailureReason, type WriteMode } from "../utils/json.js" +import { pathInside } from "../utils/paths.js" +import { realpathWithRetry } from "../utils/realpath.js" +import { type WarningSink, warningFrom } from "../utils/warnings.js" + +export type { WriteMode } + +export interface WriteOutcome { + readonly mode: WriteMode + readonly reason?: PatchFailureReason | undefined +} +import { + DEFAULT_NOTEBOOK_FORMAT, + detectNotebookFormat, + rewriteNotebookTextDetailed, + safeParseJson, + stringifyNotebook, + type NotebookFormat +} from "../utils/json.js" import { MAX_NOTEBOOK_BYTES } from "../utils/limits.js" import { replaceFile } from "../utils/atomic-replace.js" +import { afterRenameHook, beforeRenameHook } from "../utils/rename-hook.js" -interface NotebookFileServiceOptions { - /** When set, real paths are pinned and checked against this worktree. */ +export interface NotebookFileServiceOptions { readonly worktree?: string + readonly warningSink?: WarningSink | undefined + readonly signal?: AbortSignal | undefined +} + +// A parent-directory swap can move the temp file along with the directory, so +// the writer's remembered path stops existing. The temp name carries a UUID, so +// it is unambiguous: look in the original directory, its parent, and each +// sibling directory of the parent (a swapped directory is normally a sibling). +// Bounded and cheap compared with losing the full notebook as a hidden .tmp. +const locateTemp = async ( + known: string, + base: string, + sink: WarningSink | undefined +): Promise => { + const exists = (candidate: string): Promise => + fsp.stat(candidate).then( + (stat) => stat.isFile(), + () => false + ) + if (await exists(known)) return known + const parent = path.dirname(known) + const grandParent = path.dirname(parent) + const candidates = [path.join(grandParent, base)] + const siblings = await fsp.readdir(grandParent, { withFileTypes: true }).catch((error: unknown) => { + sink?.add( + warningFrom( + "temp-unlink", + error, + `could not list ${grandParent} while looking for ${base}` + ) + ) + return [] + }) + for (const entry of siblings) { + if (entry.isDirectory()) candidates.push(path.join(grandParent, entry.name, base)) + } + for (const candidate of candidates) { + if (await exists(candidate)) return candidate + } + return undefined +} + +const isMissingPath = (error: unknown): boolean => { + const code = (error as NodeJS.ErrnoException | undefined)?.code + return code === "ENOENT" || code === "ENOTDIR" +} + +const reportLockFailure = ( + sink: WarningSink | undefined, + context: string, + error: unknown +): void => { + if (!isMissingPath(error)) sink?.add(warningFrom("lock", error, context)) } -const inside = (root: string, target: string): boolean => { - const relative = path.relative(root, target) - return ( - relative === "" || - (relative !== ".." && - !relative.startsWith(`..${path.sep}`) && - !path.isAbsolute(relative)) - ) +const probeRealpath = async ( + sink: WarningSink | undefined, + target: string +): Promise => { + try { + return await realpathWithRetry(target) + } catch (error) { + if (!isMissingPath(error)) { + sink?.add(warningFrom("path-resolution", error, `resolving ${target}`)) + } + return undefined + } +} + +const probeStat = async ( + sink: WarningSink | undefined, + target: string +): Promise => { + try { + return await fsp.stat(target) + } catch (error) { + if (!isMissingPath(error)) { + sink?.add(warningFrom("path-resolution", error, `inspecting ${target}`)) + } + return undefined + } } +const utf8Decoder = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }) + +const decodeNotebookBytes = ( + bytes: Uint8Array, + filePath: string +): Effect.Effect => + Effect.try({ + try: () => utf8Decoder.decode(bytes), + catch: () => + new NotebookParseError({ + message: "the notebook is not valid UTF-8", + filePath + }) + }) + export interface NotebookFileServiceShape { readonly read: ( filePath: string @@ -44,12 +148,19 @@ export interface NotebookFileServiceShape { filePath: string ) => Effect.Effect< string, - NotebookNotFoundError | NotebookValidationError | PathOutsideWorktreeError + | NotebookNotFoundError + | NotebookParseError + | NotebookValidationError + | PathOutsideWorktreeError > readonly readWithText: ( filePath: string ) => Effect.Effect< - { readonly notebook: NotebookRaw; readonly text: string }, + { + readonly notebook: NotebookRaw + readonly text: string + readonly format: NotebookFormat + }, | NotebookNotFoundError | NotebookParseError | NotebookValidationError @@ -58,9 +169,14 @@ export interface NotebookFileServiceShape { readonly writeAtomic: ( filePath: string, notebook: NotebookRaw, - options?: { readonly noFollowFinal?: boolean } + options?: { + readonly noFollowFinal?: boolean + readonly format?: NotebookFormat + readonly previousText?: string + readonly trusted?: boolean + } ) => Effect.Effect< - void, + WriteOutcome, | NotebookParseError | NotebookValidationError | NotebookWriteError @@ -72,9 +188,6 @@ export interface NotebookFileServiceShape { ) => Effect.Effect } -// The lock registry is module-scoped on purpose: buildServices() creates a -// fresh NotebookFileService for every tool call, so instance-local locks would -// not serialize concurrent edits of the same notebook. interface FileLock { readonly sem: Semaphore.Semaphore active: number @@ -86,11 +199,22 @@ const buildFileService = ( options: NotebookFileServiceOptions = {} ): NotebookFileServiceShape => { const worktree = options.worktree + const warningSink = options.warningSink + const abortSignal = options.signal + const assertNotAborted = (): void => { + if (abortSignal?.aborted === true) { + throw new NotebookValidationError({ + message: "the request was cancelled; nothing was changed", + filePath: "", + issues: ["the tool call was cancelled by the host"] + }) + } + } const resolveInside = async (filePath: string): Promise => { if (worktree === undefined) return filePath - const root = await fsp.realpath(worktree).catch(() => worktree) - const real = await fsp.realpath(filePath) - if (!inside(root, real)) { + const root = await realpathWithRetry(worktree).catch(() => worktree) + const real = await realpathWithRetry(filePath) + if (!pathInside(root, real)) { throw new PathOutsideWorktreeError({ message: "path resolves outside of the worktree (symlink)", filePath, @@ -112,7 +236,10 @@ const buildFileService = ( filePath: string ): Effect.Effect< string, - NotebookNotFoundError | NotebookValidationError | PathOutsideWorktreeError + | NotebookNotFoundError + | NotebookParseError + | NotebookValidationError + | PathOutsideWorktreeError > => Effect.tryPromise({ try: async () => { @@ -133,9 +260,6 @@ const buildFileService = ( issues: [`size=${stat.size}`] }) } - // Open without following the final path component and with - // O_NONBLOCK: if the path is swapped to a FIFO between stat and - // open, the open does not hang and fstat rejects it. const noFollow = process.platform === "win32" ? 0 : fsConstants.O_NOFOLLOW const nonBlock = @@ -143,15 +267,12 @@ const buildFileService = ( const root = worktree === undefined ? undefined - : await fsp.realpath(worktree).catch(() => worktree) - // When confinement is enabled, resolved is already the real path. - // Opening it directly with O_NOFOLLOW rejects a link swapped in - // after resolveInside. Without confinement, resolve the alias first. + : await realpathWithRetry(worktree).catch(() => worktree) const target = worktree === undefined - ? await fsp.realpath(resolved).catch(() => resolved) + ? await realpathWithRetry(resolved).catch(() => resolved) : resolved - if (root !== undefined && !inside(root, target)) { + if (root !== undefined && !pathInside(root, target)) { throw new PathOutsideWorktreeError({ message: "path resolves outside of the worktree (symlink swap)", filePath, @@ -178,9 +299,21 @@ const buildFileService = ( issues: [`size=${opened.size}`] }) } - return await handle.readFile({ encoding: "utf8" }) + const bytes = await handle.readFile() + try { + return utf8Decoder.decode(bytes) + } catch { + throw new NotebookParseError({ + message: "the notebook is not valid UTF-8", + filePath + }) + } } finally { - await handle.close().catch(() => {}) + await handle.close().catch((error: unknown) => { + warningSink?.add( + warningFrom("cleanup", error, `closing ${filePath}`) + ) + }) } } catch (err) { const code = (err as NodeJS.ErrnoException).code @@ -198,46 +331,58 @@ const buildFileService = ( ? err : err instanceof NotebookNotFoundError ? err - : err instanceof NotebookValidationError + : err instanceof NotebookParseError ? err - : new NotebookValidationError({ - message: `cannot read notebook: ${ - err instanceof Error ? err.message : String(err) - }`, - filePath, - issues: [ - (err as NodeJS.ErrnoException).code ?? - "read failed" - ] - }) + : err instanceof NotebookValidationError + ? err + : new NotebookValidationError({ + message: `cannot read notebook: ${ + err instanceof Error ? err.message : String(err) + }`, + filePath, + issues: [ + (err as NodeJS.ErrnoException).code ?? + "read failed" + ] + }) }) - const parseAndValidate = ( - text: string, + const validateNotebookShape = ( + value: unknown, filePath: string - ): Effect.Effect => + ): Effect.Effect => Effect.gen(function* () { - const raw = yield* safeParseJson(text, filePath) - const parsed = NotebookSchema.safeParse(raw) + const parsed = NotebookSchema.safeParse(value) if (!parsed.success) { - const issues = parsed.error.issues.map( - (i) => `${i.path.join(".") || ""}: ${i.message}` - ) + const describe = ( + issue: { path: PropertyKey[]; message: string; code?: string; errors?: unknown }, + prefix: string + ): string[] => { + const path = [prefix, ...issue.path.map(String)].filter(Boolean).join(".") + if (issue.code === "invalid_union" && Array.isArray(issue.errors)) { + const nested = (issue.errors as Array>) + .flat() + .flatMap((inner) => describe(inner, path)) + return nested.length > 0 ? nested : [`${path || ""}: ${issue.message}`] + } + return [`${path || ""}: ${issue.message}`] + } + const issues = parsed.error.issues.flatMap((issue) => describe(issue, "")) return yield* new NotebookValidationError({ message: "schema validation failed", filePath, issues }) } - const nb = parsed.data - if (nb.nbformat < 4) { + const data = parsed.data + if (data.nbformat < 4) { return yield* new NotebookValidationError({ - message: `unsupported nbformat ${nb.nbformat} (must be >= 4)`, + message: `unsupported nbformat ${data.nbformat} (must be >= 4)`, filePath, - issues: [`nbformat ${nb.nbformat} < 4`] + issues: [`nbformat ${data.nbformat} < 4`] }) } - for (const [idx, cell] of nb.cells.entries()) { + for (const [idx, cell] of data.cells.entries()) { if (cell.cell_type === "code") { if (typeof cell.execution_count !== "number" && cell.execution_count !== null) { return yield* new NotebookValidationError({ @@ -248,22 +393,109 @@ const buildFileService = ( } } } - return nb + return data + }) + + const parseAndValidate = ( + text: string, + filePath: string + ): Effect.Effect => + Effect.gen(function* () { + const raw = yield* safeParseJson(text, filePath) + yield* validateNotebookShape(raw, filePath) + return applyNotebookDefaults(raw) + }) + + const readExistingText = ( + filePath: string + ): Effect.Effect => + Effect.gen(function* () { + const outcome = yield* Effect.promise(async () => { + try { + const stat = await fsp.stat(filePath) + if (!stat.isFile()) return { kind: "unreadable" as const, detail: "not a regular file" } + if (stat.size > MAX_NOTEBOOK_BYTES) { + return { + kind: "unreadable" as const, + detail: `size=${stat.size} exceeds the ${MAX_NOTEBOOK_BYTES} byte limit` + } + } + const bytes = await fsp.readFile(filePath) + return { kind: "read" as const, bytes } + } catch (error) { + const code = (error as NodeJS.ErrnoException).code + if (code === "ENOENT" || code === "ENOTDIR") { + return { kind: "absent" as const } + } + return { + kind: "unreadable" as const, + detail: (error as NodeJS.ErrnoException).code ?? (error instanceof Error ? error.message : String(error)) + } + } + }) + if (outcome.kind === "absent") return undefined + if (outcome.kind === "unreadable") { + return yield* new NotebookValidationError({ + message: "the existing notebook could not be read; refusing to overwrite it", + filePath, + issues: [outcome.detail, "fix the file permissions or remove the file explicitly"] + }) + } + return yield* decodeNotebookBytes(outcome.bytes, filePath) }) const writeAtomic = ( filePath: string, notebook: NotebookRaw, - options?: { readonly noFollowFinal?: boolean } + options?: { + readonly noFollowFinal?: boolean + readonly format?: NotebookFormat + readonly previousText?: string + readonly trusted?: boolean + } ): Effect.Effect< - void, + WriteOutcome, | NotebookParseError | NotebookValidationError | NotebookWriteError | PathOutsideWorktreeError > => Effect.gen(function* () { - const serialized = stringifyNotebook(notebook) + const stored = + options?.format !== undefined && options?.previousText !== undefined + ? undefined + : yield* readExistingText(filePath) + const format = options?.format ?? (stored === undefined ? DEFAULT_NOTEBOOK_FORMAT : detectNotebookFormat(stored)) + const previousText = options?.previousText ?? stored + const rewrite = yield* Effect.try({ + try: () => + previousText === undefined + ? { text: stringifyNotebook(notebook, format), mode: "fallback" as const, reason: undefined } + : rewriteNotebookTextDetailed(previousText, notebook, format), + catch: (error) => + new NotebookValidationError({ + message: + error instanceof RangeError + ? `notebook nesting exceeds the supported depth of ${MAX_JSON_DEPTH}` + : `the notebook cannot be serialized to JSON: ${error instanceof Error ? error.message : String(error)}`, + filePath, + issues: [ + error instanceof RangeError + ? "reduce the nesting of the metadata or output values and retry" + : "remove values JSON cannot represent (undefined, BigInt, cyclic references) and retry" + ] + }) + }) + if (rewrite.reason === "too-deep") { + return yield* new NotebookValidationError({ + message: `notebook nesting exceeds the supported depth of ${MAX_JSON_DEPTH}`, + filePath, + issues: [ + "reduce the nesting of the metadata or output values and retry" + ] + }) + } + const serialized = rewrite.text if (Buffer.byteLength(serialized, "utf8") > MAX_NOTEBOOK_BYTES) { return yield* new NotebookValidationError({ message: `refusing to write a notebook larger than ${MAX_NOTEBOOK_BYTES} bytes`, @@ -271,28 +503,35 @@ const buildFileService = ( issues: ["split the notebook or reduce large outputs"] }) } - yield* parseAndValidate(serialized, filePath) - yield* Effect.tryPromise({ - try: async () => { - const dir = path.dirname(filePath) + if (options?.trusted !== true) { + yield* validateNotebookShape(notebook, filePath) + } + if ( + options?.previousText === undefined && + previousText !== undefined && + serialized === previousText + ) { + return rewrite + } + return yield* Effect.uninterruptible( + Effect.tryPromise({ + try: async () => { + const dir = path.dirname(filePath) const root = worktree === undefined ? undefined - : await fsp.realpath(worktree).catch(() => worktree) + : (await probeRealpath(warningSink, worktree)) ?? worktree if (root !== undefined) { - // Resolve the deepest existing ancestor before mkdir. This accepts - // a lexical session path whose real target is inside the worktree - // while still rejecting an ancestor symlink that escapes it. let probe = dir let ancestorReal: string | undefined for (let depth = 0; depth < 128; depth += 1) { - ancestorReal = await fsp.realpath(probe).catch(() => undefined) + ancestorReal = await probeRealpath(warningSink, probe) if (ancestorReal !== undefined) break const next = path.dirname(probe) if (next === probe) break probe = next } - if (ancestorReal === undefined || !inside(root, ancestorReal)) { + if (ancestorReal === undefined || !pathInside(root, ancestorReal)) { throw new PathOutsideWorktreeError({ message: "path resolves outside of the worktree (symlink)", filePath, @@ -303,10 +542,10 @@ const buildFileService = ( await fsp.mkdir(dir, { recursive: true }) const dirReal = worktree === undefined - ? await fsp.realpath(dir).catch(() => dir) + ? (await probeRealpath(warningSink, dir)) ?? dir : await (async () => { - const real = await fsp.realpath(dir) - if (!inside(root!, real)) { + const real = await realpathWithRetry(dir) + if (!pathInside(root!, real)) { throw new PathOutsideWorktreeError({ message: "path resolves outside of the worktree (symlink)", filePath, @@ -315,24 +554,20 @@ const buildFileService = ( } return real })() - // Resolve an existing target even without a worktree root so a - // symlinked notebook is edited in place instead of replaced. const fileReal = options?.noFollowFinal === true ? undefined - : await fsp.realpath(filePath).catch(() => undefined) - if (root !== undefined && fileReal !== undefined && !inside(root, fileReal)) { + : await probeRealpath(warningSink, filePath) + if (root !== undefined && fileReal !== undefined && !pathInside(root, fileReal)) { throw new PathOutsideWorktreeError({ message: "path resolves outside of the worktree (symlink)", filePath, worktree: root }) } - // Writing a symlink alias must update the target, not replace the - // link with a second notebook. const target = fileReal ?? path.join(dirReal, path.basename(filePath)) const targetDir = path.dirname(target) - const targetStat = await fsp.stat(target).catch(() => undefined) + const targetStat = await probeStat(warningSink, target) if (targetStat?.isDirectory()) { throw new NotebookWriteError({ message: `cannot overwrite a directory: ${target}`, @@ -346,29 +581,258 @@ const buildFileService = ( targetDir, `.${path.basename(filePath)}.${process.pid}.${randomUUID()}.tmp` ) + // The parent-swap branch below can move the temp to a new directory + // before the replace fails; cleanup must unlink wherever it actually + // lives, or the full notebook content is left behind as a hidden .tmp. + let liveTmp = tmp + const extraCleanup: string[] = [] try { - await fsp.writeFile(tmp, serialized, { - encoding: "utf8", - flag: "wx", - mode: existingMode ?? 0o600 - }) + if (options?.previousText !== undefined) { + let current: string | undefined + try { + current = await fsp.readFile(target, { encoding: "utf8" }) + } catch (revisionError) { + const code = (revisionError as NodeJS.ErrnoException).code + if (code !== "ENOENT" && code !== "ENOTDIR") { + warningSink?.add( + warningFrom( + "revision-check", + revisionError, + "could not verify the notebook revision before writing" + ) + ) + throw new NotebookValidationError({ + message: + "the notebook revision could not be verified before the write", + filePath, + issues: [ + "the file could not be read; fix its permissions or remove it explicitly" + ] + }) + } + } + if (current !== undefined && current !== options.previousText) { + throw new NotebookValidationError({ + message: "notebook changed while the tool was editing it", + filePath, + issues: [ + "the notebook was modified externally; re-read it and retry the edit" + ] + }) + } + if (current === options.previousText && serialized === previousText) { + return rewrite + } + } + assertNotAborted() + const handle = await fsp.open(tmp, "wx", existingMode ?? 0o600) + try { + await handle.writeFile(serialized, "utf8") + await handle.sync() + } finally { + await handle.close() + } if (existingMode !== undefined) await fsp.chmod(tmp, existingMode) - await replaceFile(tmp, target) - } catch (err) { - await fsp.unlink(tmp).catch((e: NodeJS.ErrnoException) => { - if (e.code !== "ENOENT") throw e + const tempStat = await fsp.stat(tmp).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + warningSink?.add( + warningFrom("revision-check", error, `inspecting ${tmp}`) + ) + } + return undefined + }) + const freshDir = await probeRealpath(warningSink, path.dirname(target)) + await beforeRenameHook(target) + if (freshDir === undefined) { + throw new NotebookWriteError({ + message: "the notebook directory disappeared before the write", + filePath + }) + } + if (root !== undefined && !pathInside(root, freshDir)) { + throw new PathOutsideWorktreeError({ + message: "path resolves outside of the worktree (symlink swap)", + filePath, + worktree: root + }) + } + const rechecked = await probeRealpath(warningSink, path.dirname(target)) + if (rechecked === undefined || (root !== undefined && !pathInside(root, rechecked))) { + throw new PathOutsideWorktreeError({ + message: "path resolves outside of the worktree (symlink swap)", + filePath, + worktree: root ?? "" + }) + } + const freshTarget = path.join(rechecked, path.basename(target)) + if (freshTarget !== target) { + const besideFresh = path.join(freshDir, path.basename(tmp)) + const moved = await fsp.rename(tmp, besideFresh).then( + () => { + liveTmp = besideFresh + return besideFresh + }, + () => tmp + ) + // If the temp could not follow the directory (the parent is gone + // or a different filesystem), it is still at the original path in + // the moved-aside directory; record every place it may live so the + // failure cleanup removes it. + extraCleanup.push(path.join(path.dirname(target), path.basename(tmp))) + await replaceFile(moved, freshTarget, warningSink) + } else { + await replaceFile(tmp, target, warningSink) + } + await afterRenameHook(freshTarget) + // The content is fsynced before the rename; without syncing the + // directory too, a crash can lose the rename itself on ext4 with + // data=writeback, leaving the old content visible even though the + // call returned success. Windows cannot open a directory for sync, + // and the win32 replace path is already modelled separately. + if (process.platform !== "win32") { + await fsp.open(path.dirname(freshTarget), "r").then(async (dirHandle) => { + try { + await dirHandle.sync() + } finally { + await dirHandle.close() + } + }).catch((error: unknown) => { + warningSink?.add( + warningFrom( + "revision-check", + error, + `could not sync the directory of ${freshTarget} after the rename` + ) + ) + }) + } + const finalStat = await fsp.stat(freshTarget).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + warningSink?.add( + warningFrom( + "revision-check", + error, + `inspecting ${freshTarget} after the write` + ) + ) + } + return undefined }) + if ( + tempStat !== undefined && + finalStat !== undefined && + tempStat.ino !== 0 && + finalStat.ino !== 0 && + tempStat.ino !== finalStat.ino + ) { + throw new NotebookValidationError({ + message: + "another process replaced the notebook right after the write", + filePath, + issues: [ + "the notebook was written concurrently; re-read it and retry the edit" + ] + }) + } + if (finalStat === undefined) { + throw new NotebookValidationError({ + message: "the notebook disappeared right after the write", + filePath, + issues: [ + "another process removed the file; re-create it and retry the edit" + ] + }) + } + if ( + tempStat !== undefined && + tempStat.ino === finalStat.ino + ) { + const landed = await fsp.readFile(freshTarget, "utf8").catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + warningSink?.add( + warningFrom("revision-check", error, `reading ${freshTarget} after the write`) + ) + } + return undefined + }) + if (landed !== undefined && landed !== serialized) { + throw new NotebookValidationError({ + message: + "another process rewrote the notebook right after the write", + filePath, + issues: [ + "the notebook was written concurrently; re-read it and retry the edit" + ] + }) + } + } + if (previousText !== undefined && rewrite.mode !== "patched") { + warningSink?.add( + warningFrom( + "json-patch", + new Error( + `the notebook was rewritten from scratch instead of patched (${rewrite.reason ?? "fallback"})` + ), + `reformatted ${filePath}` + ) + ) + } + } catch (err) { + const known = [...new Set([liveTmp, tmp, ...extraCleanup])] + const found = new Set() + for (const candidate of known) { + try { + await fsp.unlink(candidate) + found.add(candidate) + } catch (unlinkError) { + const code = (unlinkError as NodeJS.ErrnoException).code + if (code !== "ENOENT") { + warningSink?.add( + warningFrom("temp-unlink", unlinkError, `left ${candidate}`) + ) + found.add(candidate) + } + } + } + // A parent swap can leave a second copy behind (the symlink target and + // the moved-aside directory). Sweep by the unique temp name every time, + // not only when the remembered paths failed to unlink. + const base = path.basename(tmp) + const relocated = await locateTemp(tmp, base, warningSink) + if (relocated !== undefined && !found.has(relocated)) { + try { + await fsp.unlink(relocated) + found.add(relocated) + } catch (unlinkError) { + warningSink?.add( + warningFrom("temp-unlink", unlinkError, `left ${relocated}`) + ) + } + } + if (found.size === 0 && relocated === undefined) { + warningSink?.add( + warningFrom( + "temp-unlink", + new Error(`could not locate ${base} to remove it`), + `a temp file from the failed write may remain in the worktree` + ) + ) + } throw err } + return rewrite }, catch: (err) => err instanceof PathOutsideWorktreeError ? err - : new NotebookWriteError({ - message: err instanceof Error ? err.message : String(err), - filePath - }) - }) + : err instanceof NotebookValidationError + ? err + : new NotebookWriteError({ + message: err instanceof Error ? err.message : String(err), + filePath + }) + }) + ) }) return { @@ -382,30 +846,47 @@ const buildFileService = ( Effect.gen(function* () { const text = yield* readText(filePath) const notebook = yield* parseAndValidate(text, filePath) - return { notebook, text } + return { notebook, text, format: detectNotebookFormat(text) } }), writeAtomic, withFileLock: (filePath, program) => Effect.gen(function* () { + let lockFailureReported = false + const reportLock = (context: string, error: unknown): void => { + if (lockFailureReported) return + lockFailureReported = true + reportLockFailure(warningSink, context, error) + } const key = yield* Effect.tryPromise({ try: async () => { - const real = await fsp.realpath(filePath).catch(() => undefined) + const real = await realpathWithRetry(filePath).catch((error: unknown) => { + reportLock("resolving the lock key", error) + return undefined + }) if (real !== undefined) return real - const parent = await fsp - .realpath(path.dirname(filePath)) - .catch(() => path.dirname(filePath)) + const parent = await realpathWithRetry(path.dirname(filePath)) + .catch((error: unknown) => { + reportLock("resolving the lock key parent", error) + return path.dirname(filePath) + }) return path.join(parent, path.basename(filePath)) }, - catch: () => path.resolve(filePath) - }).pipe(Effect.orElseSucceed(() => path.resolve(filePath))) + catch: (error) => { + reportLock("resolving the lock key", error) + return path.resolve(filePath) + } + }).pipe( + Effect.orElseSucceed((error) => { + reportLock("resolving the lock key", error) + return path.resolve(filePath) + }) + ) const lock = getOrCreateLock(key) lock.active += 1 return yield* lock.sem.withPermit(program).pipe( Effect.ensuring( Effect.sync(() => { lock.active -= 1 - // Do not keep a semaphore forever for a one-off path. A new - // caller either reuses it before this check or creates a new one. if (lock.active === 0 && locks.get(key) === lock) { locks.delete(key) } @@ -417,5 +898,3 @@ const buildFileService = ( } export const makeNotebookFileService = buildFileService - -export const _schemas: { readonly NotebookSchema: typeof NotebookSchema } = { NotebookSchema } diff --git a/src/services/NotebookInspectService.ts b/src/services/NotebookInspectService.ts index dc7ea6e..c701c92 100644 --- a/src/services/NotebookInspectService.ts +++ b/src/services/NotebookInspectService.ts @@ -306,11 +306,6 @@ const build = ( }) }) -/** - * Standalone Effect: detect imports that the user's Python cannot resolve. - * Pass the result of `pythonSvc.probe()` for `pythonPath`; the analyzer skips - * itself when the probe says "none" (no Python on PATH). - */ export const analyzeMissingPackagesForPython = ( notebook: NotebookRaw, pythonPath: string, diff --git a/src/services/NotebookOutputService.ts b/src/services/NotebookOutputService.ts index 7d210c8..6ad0db6 100644 --- a/src/services/NotebookOutputService.ts +++ b/src/services/NotebookOutputService.ts @@ -20,6 +20,7 @@ import { } from "./PermissionService.js" import { formatOutputs, type OutputFormatOptions } from "../format/outputs.js" import type { CellRaw, CodeCellRaw } from "../domain/cell.js" +import type { PatchFailureReason, WriteMode } from "../utils/json.js" export type OutputOperation = "list" | "read" | "read_error" | "clear_cell" | "clear_all" @@ -66,6 +67,8 @@ export interface ClearOutputsResult { readonly clearedCells: number readonly removedOutputs: number readonly removedExecutionCounts: number + readonly writeMode: WriteMode | undefined + readonly writeModeReason?: PatchFailureReason | undefined } export interface NotebookOutputServiceShape { @@ -376,7 +379,8 @@ const makeOutputImpl = ( absPath: abs, clearedCells: 0, removedOutputs: 0, - removedExecutionCounts: 0 + removedExecutionCounts: 0, + writeMode: undefined } } const code = cell as CodeCellRaw @@ -388,7 +392,8 @@ const makeOutputImpl = ( absPath: abs, clearedCells: 0, removedOutputs: 0, - removedExecutionCounts: 0 + removedExecutionCounts: 0, + writeMode: undefined } } const lexicalPaths = yield* permSvc.aliases(abs) @@ -413,15 +418,20 @@ const makeOutputImpl = ( cells[cellIndex] = newCell const newNotebook = { ...notebook, cells } yield* assertRevisionUnchanged(fileSvc, pinned, revision) - yield* fileSvc.writeAtomic(pinned, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(pinned, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) return { displayPath: pathSvc.toDisplay(abs), absPath: abs, clearedCells: 1, removedOutputs, - removedExecutionCounts: removedExec + removedExecutionCounts: removedExec, + writeMode: write.mode, + writeModeReason: write.reason } }) ) @@ -463,7 +473,8 @@ const makeOutputImpl = ( absPath: abs, clearedCells: 0, removedOutputs: 0, - removedExecutionCounts: 0 + removedExecutionCounts: 0, + writeMode: undefined } } const lexicalPaths = yield* permSvc.aliases(abs) @@ -485,15 +496,20 @@ const makeOutputImpl = ( }) const newNotebook = { ...notebook, cells } yield* assertRevisionUnchanged(fileSvc, pinned, revision) - yield* fileSvc.writeAtomic(pinned, newNotebook, { - noFollowFinal: true + const write = yield* fileSvc.writeAtomic(pinned, newNotebook, { + noFollowFinal: true, + format: snapshot.format, + previousText: snapshot.text, +trusted: true }) return { displayPath: pathSvc.toDisplay(abs), absPath: abs, clearedCells: cleared, removedOutputs, - removedExecutionCounts: removedExec + removedExecutionCounts: removedExec, + writeMode: write.mode, + writeModeReason: write.reason } }) ) diff --git a/src/services/NotebookReadService.ts b/src/services/NotebookReadService.ts index ed7a3f1..1cca594 100644 --- a/src/services/NotebookReadService.ts +++ b/src/services/NotebookReadService.ts @@ -167,8 +167,6 @@ export const makeReadImpl = ( }), readRange: (filePath, start, end, options) => Effect.gen(function* () { - // Clamp before allocating: a model-supplied end of 50_000_000 must - // not build a 50-million-element array. const { abs, notebook } = yield* loadNotebook(filePath) const lo = Math.max(0, Math.min(start, end)) if (lo >= notebook.cells.length) { diff --git a/src/services/PathService.ts b/src/services/PathService.ts index 6602e99..3fb23e7 100644 --- a/src/services/PathService.ts +++ b/src/services/PathService.ts @@ -4,6 +4,7 @@ import * as path from "node:path" import * as fs from "node:fs" import * as fsp from "node:fs/promises" import { replaceFile } from "../utils/atomic-replace.js" +import { type WarningSink, warningFrom } from "../utils/warnings.js" import { NotebookNotFoundError, NotebookWriteError, @@ -14,6 +15,7 @@ import { isAbsolutePath, makeRelative, normalizeSlashes, + absoluteDriveRoot, resolveAgainstBase, toForwardSlashes } from "../utils/paths.js" @@ -25,6 +27,15 @@ export interface PathEnv { readonly allowOutsideWorktree?: boolean | undefined } +export interface PathServiceOptions extends PathEnv { + readonly warningSink?: WarningSink | undefined +} + +const isMissingPath = (error: unknown): boolean => { + const code = (error as NodeJS.ErrnoException | undefined)?.code + return code === "ENOENT" || code === "ENOTDIR" +} + export interface PathServiceShape { readonly env: PathEnv readonly resolve: (inputPath: string) => Effect.Effect @@ -46,21 +57,40 @@ const pathNorm = (p: string, platform: NodeJS.Platform): string => { if (!p) { return p } - const resolved = path.resolve(p) + const resolved = path.resolve(absoluteDriveRoot(p, platform)) return platform === "win32" ? normalizeSlashes(resolved, platform) : resolved } -const buildPathService = (env: PathEnv): PathServiceShape => { +const buildPathService = (options: PathServiceOptions): PathServiceShape => { + const env: PathEnv = { + directory: options.directory, + worktree: options.worktree, + platform: options.platform, + ...(options.allowOutsideWorktree === undefined + ? {} + : { allowOutsideWorktree: options.allowOutsideWorktree }) + } + const sink = options.warningSink const worktreeResolved = pathNorm(env.worktree, env.platform) const directoryResolved = pathNorm(env.directory, env.platform) const allowOutside = env.allowOutsideWorktree === true + const makeWalkReporter = (): ((context: string, error: unknown) => void) => { + let reported = false + return (context, error) => { + if (reported || isMissingPath(error)) return + reported = true + sink?.add(warningFrom("path-resolution", error, context)) + } + } + const inside = (base: string, abs: string): boolean => { + const baseNorm = pathNorm(base, env.platform) const norm = pathNorm(abs, env.platform) - if (norm === base) { + if (norm === baseNorm) { return true } - const rel = path.relative(base, norm) + const rel = path.relative(baseNorm, norm) if (!rel) { return true } @@ -101,17 +131,21 @@ const buildPathService = (env: PathEnv): PathServiceShape => { if (allowOutside) { return } + const reportWalk = makeWalkReporter() const worktreeReal = await fs.promises .realpath(worktreeResolved) - .catch(() => worktreeResolved) - // Walk up to the deepest existing component. This catches symlinked - // ancestors and dangling symlink targets that realpath(absPath) - // alone cannot resolve. + .catch((error: unknown) => { + reportWalk("resolving the worktree root", error) + return worktreeResolved + }) const assertPath = async (candidate: string, depth = 0): Promise => { if (depth > 64) { throw outsideError(absPath, "path has too many symlink levels") } - const real = await fs.promises.realpath(candidate).catch(() => undefined) + const real = await fs.promises.realpath(candidate).catch((error: unknown) => { + reportWalk(`resolving ${candidate}`, error) + return undefined + }) if (real !== undefined) { if (!inside(worktreeReal, real)) { throw outsideError(absPath, "path resolves outside of the worktree (symlink)") @@ -121,9 +155,17 @@ const buildPathService = (env: PathEnv): PathServiceShape => { const isLink = await fs.promises .lstat(candidate) .then((stat) => stat.isSymbolicLink()) - .catch(() => false) + .catch((error: unknown) => { + reportWalk(`inspecting ${candidate}`, error) + return false + }) if (isLink) { - const target = await fs.promises.readlink(candidate).catch(() => undefined) + const target = await fs.promises + .readlink(candidate) + .catch((error: unknown) => { + reportWalk(`reading the link at ${candidate}`, error) + return undefined + }) if (target !== undefined) { await assertPath(path.resolve(path.dirname(candidate), target), depth + 1) return @@ -149,6 +191,15 @@ const buildPathService = (env: PathEnv): PathServiceShape => { Effect.try({ try: () => { if (!fs.existsSync(absPath)) { + try { + fs.statSync(absPath) + } catch (error) { + if (!isMissingPath(error)) { + sink?.add( + warningFrom("path-resolution", error, `checking ${absPath}`) + ) + } + } throw new NotebookNotFoundError({ message: "file does not exist", filePath: absPath @@ -175,8 +226,12 @@ const buildPathService = (env: PathEnv): PathServiceShape => { writeFileSafe: (absPath, content, options) => Effect.tryPromise({ try: async () => { + const reportWalk = makeWalkReporter() if (options?.noFollowFinal === true) { - const existing = await fsp.lstat(absPath).catch(() => undefined) + const existing = await fsp.lstat(absPath).catch((error: unknown) => { + reportWalk(`inspecting ${absPath}`, error) + return undefined + }) if (existing?.isSymbolicLink()) { throw new NotebookWriteError({ message: "refusing to write through a symlink at the pinned target", @@ -191,17 +246,28 @@ const buildPathService = (env: PathEnv): PathServiceShape => { `.${path.basename(target)}.${process.pid}.${randomBytes(6).toString("hex")}.tmp` ) try { - const existing = await fsp.lstat(target).catch(() => undefined) - await fsp.writeFile(temp, content, { - encoding: "utf8", - flag: "wx", - mode: - existing !== undefined && !existing.isSymbolicLink() - ? existing.mode & 0o777 - : 0o600 + const existing = await fsp.lstat(target).catch((error: unknown) => { + reportWalk(`inspecting ${target}`, error) + return undefined }) + // Write through a handle so the content is fsynced before the + // rename: without it a crash loses an export that the tool + // already reported as written. + const handle = await fsp.open(temp, "wx", existing !== undefined && !existing.isSymbolicLink() + ? existing.mode & 0o777 + : 0o600) + try { + await handle.writeFile(content, "utf8") + await handle.sync() + } finally { + await handle.close() + } if (existing !== undefined && !existing.isSymbolicLink()) { - await fsp.chmod(temp, existing.mode & 0o777).catch(() => {}) + await fsp.chmod(temp, existing.mode & 0o777).catch((error: unknown) => { + sink?.add( + warningFrom("atomic-replace", error, `preserving the mode of ${target}`) + ) + }) } if (existing?.isDirectory()) { throw new NotebookWriteError({ @@ -209,9 +275,24 @@ const buildPathService = (env: PathEnv): PathServiceShape => { filePath: absPath }) } - await replaceFile(temp, target) + await replaceFile(temp, target, sink) + if (process.platform !== "win32") { + await fsp.open(path.dirname(target), "r").then(async (dirHandle) => { + try { + await dirHandle.sync() + } finally { + await dirHandle.close() + } + }).catch((error: unknown) => { + sink?.add( + warningFrom("atomic-replace", error, `syncing the directory of ${target}`) + ) + }) + } } catch (error) { - await fsp.rm(temp, { force: true }).catch(() => {}) + await fsp.rm(temp, { force: true }).catch((cleanupError: unknown) => { + sink?.add(warningFrom("temp-unlink", cleanupError, `left ${temp}`)) + }) throw error } } @@ -222,22 +303,27 @@ const buildPathService = (env: PathEnv): PathServiceShape => { const existingReal = options?.noFollowFinal === true ? undefined - : await fsp.realpath(absPath).catch(() => undefined) + : await fsp.realpath(absPath).catch((error: unknown) => { + reportWalk(`resolving ${absPath}`, error) + return undefined + }) const target = existingReal ?? absPath await writeTarget(target) return } - const root = await fsp.realpath(worktreeResolved).catch(() => worktreeResolved) + const root = await fsp.realpath(worktreeResolved).catch((error: unknown) => { + reportWalk("resolving the worktree root", error) + return worktreeResolved + }) const parent = path.dirname(absPath) - // Check the deepest existing ancestor before mkdir so an outside - // symlink cannot create directories outside the worktree as a side - // effect. This also accepts a lexical session path whose real target - // is inside the worktree. let probe = absPath let ancestorReal: string | undefined for (let depth = 0; depth < 128; depth += 1) { - ancestorReal = await fsp.realpath(probe).catch(() => undefined) + ancestorReal = await fsp.realpath(probe).catch((error: unknown) => { + reportWalk(`resolving ${probe}`, error) + return undefined + }) if (ancestorReal !== undefined) break const next = path.dirname(probe) if (next === probe) break @@ -250,7 +336,10 @@ const buildPathService = (env: PathEnv): PathServiceShape => { ) } await fsp.mkdir(parent, { recursive: true }) - const parentReal = await fsp.realpath(parent).catch(() => undefined) + const parentReal = await fsp.realpath(parent).catch((error: unknown) => { + reportWalk(`resolving ${parent}`, error) + return undefined + }) if (parentReal === undefined || !inside(root, parentReal)) { throw outsideError( absPath, @@ -260,7 +349,10 @@ const buildPathService = (env: PathEnv): PathServiceShape => { const existingReal = options?.noFollowFinal === true ? undefined - : await fsp.realpath(absPath).catch(() => undefined) + : await fsp.realpath(absPath).catch((error: unknown) => { + reportWalk(`resolving ${absPath}`, error) + return undefined + }) if (existingReal !== undefined && !inside(root, existingReal)) { throw outsideError( absPath, diff --git a/src/services/PermissionService.ts b/src/services/PermissionService.ts index d4daa19..c542a31 100644 --- a/src/services/PermissionService.ts +++ b/src/services/PermissionService.ts @@ -3,27 +3,42 @@ import { promises as fsp } from "node:fs" import * as path from "node:path" import type { ToolContext } from "../tool.js" import { PermissionDeniedError } from "../domain/errors.js" +import { pathInside } from "../utils/paths.js" +import { type WarningSink, warningFrom } from "../utils/warnings.js" -/** - * Permission resources for a write target: the lexical path the caller used - * and, when it differs, the real path that will actually be written. A rule - * that denies the real notebook must not be bypassed through a symlink alias. - */ -const inside = (root: string, target: string): boolean => { - const relative = path.relative(root, target) - return ( - relative === "" || - (relative !== ".." && - !relative.startsWith(`..${path.sep}`) && - !path.isAbsolute(relative)) - ) +const isMissingPath = (error: unknown): boolean => { + const code = (error as NodeJS.ErrnoException | undefined)?.code + return code === "ENOENT" || code === "ENOTDIR" } -export const resolveDeepReal = async (target: string): Promise => { +const reportUnlessMissing = ( + sink: WarningSink | undefined, + context: string, + error: unknown +): void => { + if (!isMissingPath(error)) sink?.add(warningFrom("permission-alias", error, context)) +} + +export interface AliasResolutionOptions { + readonly warningSink?: WarningSink | undefined +} + +export const resolveDeepReal = async ( + target: string, + options: AliasResolutionOptions = {} +): Promise => { + const sink = options.warningSink const suffix: string[] = [] let current = target + let reported = false while (true) { - const real = await fsp.realpath(current).catch(() => undefined) + const real = await fsp.realpath(current).catch((error: unknown) => { + if (!reported) { + reported = true + reportUnlessMissing(sink, `resolving ${current}`, error) + } + return undefined + }) if (real !== undefined) { return suffix.length === 0 ? real : path.join(real, ...suffix) } @@ -36,14 +51,15 @@ export const resolveDeepReal = async (target: string): Promise => { export const permissionAliases = async ( filePath: string, - bases: ReadonlyArray = [] + bases: ReadonlyArray = [], + options: AliasResolutionOptions = {} ): Promise> => { + const sink = options.warningSink const base = bases[0] ?? process.cwd() const absolute = path.isAbsolute(filePath) ? filePath : path.resolve(base, filePath) - const real = await fsp.realpath(absolute).catch(() => undefined) - const resolved = real ?? (await resolveDeepReal(absolute)) + const resolved = await resolveDeepReal(absolute, { warningSink: sink }) const out = new Set([absolute]) const addWithSlashes = (value: string): void => { out.add(value) @@ -52,16 +68,16 @@ export const permissionAliases = async ( } addWithSlashes(absolute) if (resolved !== absolute) addWithSlashes(resolved) - // OpenCode matches native read/edit resources as location-relative paths. - // Include relative aliases from both the session directory and worktree so - // rules such as "secrets/*" or "notebooks/foo.ipynb" also apply here. for (const root of bases) { const roots = new Set([path.resolve(root)]) - const realRoot = await fsp.realpath(root).catch(() => undefined) + const realRoot = await fsp.realpath(root).catch((error: unknown) => { + reportUnlessMissing(sink, `resolving the base ${root}`, error) + return undefined + }) if (realRoot !== undefined) roots.add(path.resolve(realRoot)) for (const rootAbs of roots) { for (const candidate of [absolute, resolved]) { - if (!inside(rootAbs, candidate)) continue + if (!pathInside(rootAbs, candidate)) continue const relative = path.relative(rootAbs, candidate) if (relative.length > 0) addWithSlashes(relative) } @@ -87,29 +103,43 @@ export interface PermissionServiceShape { ) => Effect.Effect, never> } -const build = (ctx: ToolContext): PermissionServiceShape => ({ - aliases: (filePath) => - Effect.promise(() => permissionAliases(filePath, [ctx.directory, ctx.worktree])), - ask: (req) => - Effect.tryPromise({ - try: async () => { - await ctx.ask({ - permission: req.kind, - patterns: [...req.patterns], - always: [...req.always], - metadata: { - ...req.metadata, - action: req.action - } - }) - }, - catch: (err) => - new PermissionDeniedError({ - message: err instanceof Error ? err.message : String(err), - action: req.action, - cause: err +export interface PermissionServiceOptions { + readonly warningSink?: WarningSink | undefined +} + +const build = ( + ctx: ToolContext, + options: PermissionServiceOptions = {} +): PermissionServiceShape => { + const sink = options.warningSink + return { + aliases: (filePath) => + Effect.promise(() => + permissionAliases(filePath, [ctx.directory, ctx.worktree], { + warningSink: sink }) - }) -}) + ), + ask: (req) => + Effect.tryPromise({ + try: async () => { + await ctx.ask({ + permission: req.kind, + patterns: [...req.patterns], + always: [...req.always], + metadata: { + ...req.metadata, + action: req.action + } + }) + }, + catch: (err) => + new PermissionDeniedError({ + message: err instanceof Error ? err.message : String(err), + action: req.action, + cause: err + }) + }) + } +} export const makePermissionService = build diff --git a/src/services/PythonService.ts b/src/services/PythonService.ts index 6c600a8..ebf2106 100644 --- a/src/services/PythonService.ts +++ b/src/services/PythonService.ts @@ -5,6 +5,7 @@ import * as os from "node:os" import * as path from "node:path" import { Effect } from "effect" import { PermissionDeniedError } from "../domain/errors.js" +import { type WarningSink, warningFrom } from "../utils/warnings.js" const HELPER_ENV_KEYS = [ "PYTHONPATH", @@ -13,19 +14,12 @@ const HELPER_ENV_KEYS = [ "PYTHONINSPECT" ] as const -/** - * Environment for the Python helper process. The helper runs first-party - * code and imports stdlib/nbclient modules before it can trust the request, - * so project-controlled PYTHONPATH/PYTHONHOME values must not reach it. - * Notebook kernels get the original values back through `kernelEnv`. - */ export const helperSpawnEnv = (): NodeJS.ProcessEnv => { const env = { ...process.env } for (const key of HELPER_ENV_KEYS) delete env[key] return env } -/** Original Python env values to restore only inside the notebook kernel. */ export const kernelEnvOverrides = (): Record | undefined => { const out: Record = {} for (const key of HELPER_ENV_KEYS) { @@ -64,8 +58,12 @@ export interface PythonServiceOptions { readonly pythonSource?: "options" | "env" | undefined } +export interface ProbeOptions { + readonly warningSink?: WarningSink | undefined +} + export interface PythonServiceShape { - readonly probe: () => Effect.Effect + readonly probe: (options?: ProbeOptions) => Effect.Effect readonly candidates: () => Effect.Effect, never> readonly checkDependencies: ( pythonPath: string @@ -74,7 +72,6 @@ export interface PythonServiceShape { pythonPath: string, module: string ) => Effect.Effect - /** Batch variant: one Python process for many imports. */ readonly checkImports?: ( pythonPath: string, modules: ReadonlyArray, @@ -88,9 +85,6 @@ export interface PythonServiceShape { ) => Effect.Effect } -// Test-only surface: cache invalidation is an implementation detail of the -// dependency check, and consumers should not depend on it. Underscore prefix -// follows the same convention as Python's "private by convention". export interface _PythonServiceForTest { readonly _invalidateDepsCache: (pythonPath?: string) => void } @@ -101,14 +95,15 @@ const REQUIRED_DEPS = ["nbformat", "nbclient", "jupyter_client", "ipykernel"] as const probeEnv = (): NodeJS.ProcessEnv => { const env = { ...process.env } - // Isolated probes must not execute project-local modules through - // PYTHONPATH or the current directory. delete env.PYTHONPATH delete env.PYTHONHOME return env } -const probeOnce = (executable: string): Promise => +const probeOnce = ( + executable: string, + onFailure?: (reason: string) => void +): Promise => new Promise((resolve) => { const child = spawn( executable, @@ -138,6 +133,7 @@ const probeOnce = (executable: string): Promise => } const timer = setTimeout(() => { kill() + onFailure?.(`timed out after ${PROBE_TIMEOUT_MS}ms`) resolve(null) }, PROBE_TIMEOUT_MS) child.stdout.on("data", (chunk: Buffer) => { @@ -152,13 +148,19 @@ const probeOnce = (executable: string): Promise => stderrBytes += take.length stderrChunks.push(take) }) - child.on("error", () => { + child.on("error", (error) => { clearTimeout(timer) + const code = (error as NodeJS.ErrnoException).code + onFailure?.(code ?? error.message) resolve(null) }) child.on("close", (code) => { clearTimeout(timer) if (code !== 0) { + const stderr = Buffer.concat(stderrChunks).toString("utf8").trim() + onFailure?.( + stderr.split(/\r?\n/).filter(Boolean).at(-1) ?? `exited with code ${code}` + ) resolve(null) return } @@ -172,9 +174,10 @@ const probeOnce = (executable: string): Promise => const probeWithFrom = async ( executable: string, - from: PythonProbeResult["from"] + from: PythonProbeResult["from"], + onFailure?: (reason: string) => void ): Promise => { - const result = await probeOnce(executable) + const result = await probeOnce(executable, onFailure) if (!result) return null return { ...result, from } } @@ -383,10 +386,6 @@ print(json.dumps(out))` const IMPORTS_BATCH_SIZE = 128 -/** - * Check many imports without exceeding platform environment/argv limits. - * Roots are deduplicated and sent in bounded chunks, preserving input order. - */ const checkImportsBatch = async ( pythonPath: string, modules: ReadonlyArray, @@ -403,8 +402,6 @@ const checkImportsBatch = async ( })) checks.push(...tooLong) const usable = roots.filter((name) => name.length <= 256) - // Windows caps the whole environment block at 32767 chars; stay well - // below it because inherited variables also count. const envBudget = process.platform === "win32" ? 16_000 : 60_000 const chunks: string[][] = [] let current: string[] = [] @@ -451,11 +448,6 @@ const checkImportsBatch = async ( ) } -/** - * Absolute PATH candidates for the Python names the plugin probes. Resolving - * them without executing lets the first shell assert cover the interpreter a - * PATH lookup will actually spawn. - */ export const pythonInterpreterResources = ( configured?: string ): ReadonlyArray => { @@ -475,18 +467,13 @@ export const pythonInterpreterResources = ( try { out.add(fs.realpathSync(candidate)) } catch { - // missing / dangling } return true } if (configured !== undefined && configured.length > 0) { - // An explicit interpreter wins: do not enumerate unused PATH Python - // installations or a deny on one of them blocks a safe configuration. if (path.isAbsolute(configured)) { add(configured) } else { - // A bare name is resolved through PATH; assert the absolute target, - // not just the literal string. Windows shims usually carry .exe. const configuredNames = process.platform === "win32" && !configured.endsWith(".exe") ? [configured, `${configured}.exe`] @@ -499,16 +486,12 @@ export const pythonInterpreterResources = ( fs.accessSync(candidate, fs.constants.X_OK) if (add(candidate)) break outer } catch { - // keep looking } } } } return [...out] } - // The probe tries `python` first and only falls back to `python3` when it - // is absent. Asserting both up front over-blocks when the unused fallback - // is denied, so include only the first name that resolves. for (const name of names) { let found = false for (const dir of dirs) { @@ -521,7 +504,6 @@ export const pythonInterpreterResources = ( break } } catch { - // not executable / missing } } if (found) break @@ -529,7 +511,6 @@ export const pythonInterpreterResources = ( return [...out] } -/** Back-compat: realpath-resolved PATH candidates only. */ export const pathPythonCandidates = (): ReadonlyArray => pythonInterpreterResources().filter((value) => { try { @@ -549,7 +530,6 @@ const findHelper = (rel: string): string | undefined => { candidates.push(rel) } else { const distDir = path.dirname(__filename) - // dist/index.js -> package root; src/services/*.ts -> repository root. candidates.push( path.basename(distDir) === "dist" ? path.resolve(distDir, "..", rel) @@ -559,10 +539,6 @@ const findHelper = (rel: string): string | undefined => { for (const c of candidates) { if (fs.existsSync(c)) return c } - // Log the candidates we tried so debugging layout issues is easier. - // Project has no logging service yet; console.warn is the only signal - // that survives in production. Deduped: chained tool calls would - // otherwise spam the same warning on every invocation. if (!findHelperWarned) { findHelperWarned = true console.warn( @@ -648,8 +624,6 @@ const makePythonImpl = ( specs.map((spec) => probeWithFrom(spec.executable, spec.from)) ) ).filter((item): item is PythonProbeResult => item !== null) - // The configured interpreter can also be the first `python` on PATH. - // Keep the higher-priority source and avoid duplicate doctor entries. const seen = new Set() return list.filter((item) => { const key = path.resolve(item.executable) @@ -659,21 +633,33 @@ const makePythonImpl = ( }) } - // Probe cache: finding an interpreter spawns up to four subprocesses. - // A short TTL keeps repeated tool calls cheap without hiding a newly - // installed Python forever. const PROBE_TTL_MS = 60_000 let candidatesCheckedAt = 0 let probed = false let selectedProbe: PythonProbeResult | undefined let selectedCheckedAt = 0 let selectedProbed = false + let configuredProbeFailure: string | undefined - const probe = (): Effect.Effect => + const warnConfiguredProbeFailure = (sink: WarningSink): void => { + const configured = opts.pythonPath + if (configured === undefined || configured.length === 0) return + sink.add( + warningFrom( + "python-probe", + new Error( + configuredProbeFailure ?? + "the configured python interpreter did not run" + ), + `pythonPath=${configured}` + ) + ) + } + + const probe = (options?: ProbeOptions): Effect.Effect => Effect.gen(function* () { + const sink = options?.warningSink const now = Date.now() - // Fresh candidates (doctor/allCandidates) win over a previously cached - // probe, so a newly installed interpreter is picked up immediately. if ( probed && candidates.length > 0 && @@ -685,19 +671,28 @@ const makePythonImpl = ( return selectedProbe } if (selectedProbed && now - selectedCheckedAt < PROBE_TTL_MS) { + if (sink !== undefined) warnConfiguredProbeFailure(sink) return selectedProbe! } - for (const attempt of selectedSpecs()) { + const specs = selectedSpecs() + for (const attempt of specs) { const found = yield* Effect.promise(() => - probeWithFrom(attempt.executable, attempt.from) + probeWithFrom(attempt.executable, attempt.from, (reason) => { + configuredProbeFailure = reason + }) ) if (found) { + configuredProbeFailure = undefined selectedProbe = found selectedCheckedAt = Date.now() selectedProbed = true return found } } + if (specs.length === 0) { + configuredProbeFailure = + "the configured path is not an absolute interpreter or PATH name" + } selectedProbe = { pythonPath: opts.pythonPath ?? "python", version: "unknown", @@ -706,6 +701,7 @@ const makePythonImpl = ( } selectedCheckedAt = Date.now() selectedProbed = true + if (sink !== undefined) warnConfiguredProbeFailure(sink) return selectedProbe }) const allCandidates = (): Effect.Effect, never> => @@ -720,9 +716,6 @@ const makePythonImpl = ( return candidates }) - // Dependency-check cache: `checkDependencies` spawns 4 Python subprocesses per - // call, so without this a 200ms notebook run would pay >=1s of dep-probe - // overhead on every `ipynb_run`. Keyed by pythonPath, with a 60s TTL. const DEPS_TTL_MS = 60_000 interface DepsCacheEntry { readonly checkedAt: number @@ -740,6 +733,19 @@ const makePythonImpl = ( } const results = await Promise.all(REQUIRED_DEPS.map((m) => checkImport(pythonPath, m))) depsCache.set(pythonPath, { checkedAt: Date.now(), results }) + // TTL only marks an entry stale; bound the map so a host that probes many + // interpreters does not keep one entry per path forever. + if (depsCache.size > 32) { + let oldest: string | undefined + let oldestAt = Number.POSITIVE_INFINITY + for (const [candidate, entry] of depsCache) { + if (entry.checkedAt < oldestAt) { + oldestAt = entry.checkedAt + oldest = candidate + } + } + if (oldest !== undefined) depsCache.delete(oldest) + } return results }) diff --git a/src/services/index.ts b/src/services/index.ts index 94d5591..ddee840 100644 --- a/src/services/index.ts +++ b/src/services/index.ts @@ -18,6 +18,7 @@ import { makeExportImpl, type NotebookExportServiceShape } from "./NotebookExpor import { makeExecutionImpl, type NotebookExecutionServiceShape } from "./NotebookExecutionService.js" import { makePythonService, type PythonServiceShape } from "./PythonService.js" import { makeKernelManager, type KernelManagerShape } from "./KernelManager.js" +import type { WarningSink } from "../utils/warnings.js" export { type PathServiceShape, type PathEnv, makePathService } from "./PathService.js" export { type PermissionServiceShape, type PermissionRequest, type PermissionKind, makePermissionService } from "./PermissionService.js" @@ -52,10 +53,9 @@ export interface NotebookServices { readonly file: NotebookFileServiceShape readonly python: PythonServiceShape readonly kernel: KernelManagerShape - /** Interpreter selected from plugin options/env, when configured. */ readonly pythonPath: string | undefined - /** Invalid pythonPath configuration, surfaced by Python-dependent tools. */ readonly pythonPathError: string | undefined + readonly envOptionsError: string | undefined readonly inspect: ReturnType readonly read: NotebookReadServiceShape readonly edit: NotebookEditServiceShape @@ -86,10 +86,6 @@ const getOrCreatePythonService = (opts: { return service } -// Module-level registry for the kernel managers. The plugin needs the same -// instance across all tool invocations to share running kernels. Managers are -// grouped by plugin instance (location) and keyed by runtime configuration, so -// unloading one project cannot kill another project's kernels. const defaultKernelScope = {} const sharedKernelManagers = new Map>() @@ -99,6 +95,7 @@ const getOrCreateSharedKernelManager = ( readonly helperPath: string readonly workingDirectory: string readonly defaultTimeoutMs: number + readonly warningSink?: WarningSink | undefined }, scope?: object ): KernelManagerShape => { @@ -115,12 +112,17 @@ const getOrCreateSharedKernelManager = ( opts.defaultTimeoutMs ]) const existing = managers.get(key) - if (existing) return existing + if (existing) { + if (opts.warningSink !== undefined) existing.setWarningSink?.(opts.warningSink) + return existing + } + const sinkTarget: { sink?: WarningSink | undefined } = { sink: opts.warningSink } const manager = makeKernelManager({ pythonPath: opts.pythonPath ?? "python", helperPath: opts.helperPath, workingDirectory: opts.workingDirectory, - defaultTimeoutMs: opts.defaultTimeoutMs + defaultTimeoutMs: opts.defaultTimeoutMs, + sinkTarget }) managers.set(key, manager) return manager @@ -138,18 +140,32 @@ export const disposeSharedKernelManager = async (scope?: object): Promise await Promise.all(managers.map((manager) => Effect.runPromise(manager.disposeAll()))) } -export const buildServices = (ctx: ToolContext): NotebookServices => { +export interface BuildServicesOptions { + readonly warningSink?: WarningSink | undefined +} + +export const buildServices = ( + ctx: ToolContext, + options: BuildServicesOptions = {} +): NotebookServices => { const resolved = resolveOptionsFromEnv(ctx.pluginOptions) + const envOptionsErrorMessage = envOptionsError + const warningSink = options.warningSink const pathSvc: PathServiceShape = makePathService({ directory: ctx.directory, worktree: ctx.worktree, platform: process.platform, - allowOutsideWorktree: resolved.allowOutsideWorktree + allowOutsideWorktree: resolved.allowOutsideWorktree, + warningSink + }) + const permissionSvc: PermissionServiceShape = makePermissionService(ctx, { + warningSink + }) + const fileSvc: NotebookFileServiceShape = makeNotebookFileService({ + ...(resolved.allowOutsideWorktree ? {} : { worktree: ctx.worktree }), + warningSink, + signal: ctx.abort }) - const permissionSvc: PermissionServiceShape = makePermissionService(ctx) - const fileSvc: NotebookFileServiceShape = makeNotebookFileService( - resolved.allowOutsideWorktree ? {} : { worktree: ctx.worktree } - ) let pythonPath: string | undefined let pythonPathError: string | undefined try { @@ -177,7 +193,8 @@ export const buildServices = (ctx: ToolContext): NotebookServices => { pythonPath, helperPath: resolved.helperRelativePath, workingDirectory: ctx.directory, - defaultTimeoutMs: resolved.defaultTimeoutMs + defaultTimeoutMs: resolved.defaultTimeoutMs, + warningSink }, ctx.pluginScope ) @@ -201,6 +218,7 @@ export const buildServices = (ctx: ToolContext): NotebookServices => { kernel: kernelMgr, pythonPath, pythonPathError, + envOptionsError: envOptionsErrorMessage, inspect: inspectSvc, read: readSvc, edit: editSvc, @@ -219,24 +237,37 @@ const parseResolvedOptions = (value: unknown): PluginOptions => { let cachedEnvOptions: { readonly raw: string; readonly value: PluginOptions } | undefined const cachedInstanceOptions = new WeakMap() -const resolveOptionsFromEnv = (instanceOptions?: unknown): PluginOptions => { +let envOptionsError: string | undefined + +export const resolveOptionsFromEnv = (instanceOptions?: unknown): PluginOptions => { const raw = process.env.OPENCODE_IPYNB_OPTIONS if (raw) { - if (cachedEnvOptions?.raw === raw) return cachedEnvOptions.value + if (cachedEnvOptions?.raw === raw) { + envOptionsError = undefined + return cachedEnvOptions.value + } try { const parsed = JSON.parse(raw) as unknown const safe = PluginOptionsSchema.safeParse(parsed) - if (!safe.success) throw new Error("invalid plugin options") + if (!safe.success) { + const issue = safe.error.issues[0] + throw new Error( + issue === undefined + ? "invalid plugin options" + : `invalid plugin options: ${issue.path.join(".")} ${issue.message}` + ) + } cachedEnvOptions = { raw, value: safe.data } + envOptionsError = undefined return safe.data - } catch { - // Do not cache an instance-specific fallback under the global raw key: - // another project with different instance options would inherit it. + } catch (error) { + envOptionsError = error instanceof Error ? error.message : String(error) return instanceOptions !== undefined && instanceOptions !== null ? parseResolvedOptions(instanceOptions) : parsePluginOptions({}) } } + envOptionsError = undefined if (instanceOptions !== undefined && instanceOptions !== null) { if (typeof instanceOptions === "object") { const cached = cachedInstanceOptions.get(instanceOptions) @@ -250,4 +281,3 @@ const resolveOptionsFromEnv = (instanceOptions?: unknown): PluginOptions => { return parsePluginOptions({}) } -export { resolveOptionsFromEnv } diff --git a/src/services/revision.ts b/src/services/revision.ts index 75a1ff6..1222385 100644 --- a/src/services/revision.ts +++ b/src/services/revision.ts @@ -1,23 +1,23 @@ import { createHash } from "node:crypto" -import { promises as fsp } from "node:fs" import { Effect } from "effect" import { NotebookNotFoundError, + NotebookParseError, NotebookValidationError, PathOutsideWorktreeError } from "../domain/errors.js" import type { NotebookFileServiceShape } from "./NotebookFileService.js" +import { realpathWithRetry } from "../utils/realpath.js" type RevisionError = | NotebookNotFoundError + | NotebookParseError | NotebookValidationError | PathOutsideWorktreeError -/** Resolve the canonical target before prompting; I/O uses this pinned path. */ export const pinRealPath = (filePath: string): Effect.Effect => - Effect.promise(() => fsp.realpath(filePath).catch(() => filePath)) + Effect.promise(() => realpathWithRetry(filePath).catch(() => filePath)) -/** SHA-256 of the exact bytes on disk, used to detect external edits. */ export const contentHash = (text: string): string => createHash("sha256").update(text).digest("hex") @@ -27,10 +27,12 @@ export const readRevision = ( ): Effect.Effect => Effect.map(fileSvc.readText(absPath), contentHash) -/** - * Fail instead of overwriting a notebook that changed while the tool held it - * open (for example during an interactive permission prompt). - */ +// `writeAtomic` compares `previousText` against a re-read under the lock, so +// this check is redundant for correctness. It is kept on purpose: it runs before +// the permission prompt, so a conflict is refused before the user is asked to +// approve a write, and it narrows the window in which an external edit can slip +// between the prompt and the write. Measured cost: 34 ms on a 17 MB notebook +// (read + SHA-256), against ~500 ms for the write itself. export const assertRevisionUnchanged = ( fileSvc: NotebookFileServiceShape, absPath: string, diff --git a/src/tool.ts b/src/tool.ts index 9a2ade2..7cbb087 100644 --- a/src/tool.ts +++ b/src/tool.ts @@ -2,26 +2,16 @@ import { Cause, Effect, Exit } from "effect" import type { z } from "zod" import { PermissionDeniedError } from "./domain/errors.js" -/** - * Minimal tool contract used by the notebook implementations. - * - * The plugin is V2-only, but keeping this small internal helper lets every - * tool declare zod args once and share the same result/context shape. The V2 - * adapter converts the zod args to JSON Schema and maps results to V2 content. - */ export interface ToolContext { readonly sessionID: string readonly messageID: string readonly agent: string - /** Current project directory for this session. */ readonly directory: string - /** Project worktree root for this session. */ readonly worktree: string readonly abort: AbortSignal - /** Options from this plugin instance. */ readonly pluginOptions?: unknown - /** Identity of the plugin instance, used to scope warm-kernel cleanup. */ readonly pluginScope?: object + readonly warningSink?: import("./utils/warnings.js").WarningSink | undefined metadata(input: { title?: string metadata?: Record @@ -65,14 +55,21 @@ export type AnyToolDefinition = ToolDefinition export const tool = ( definition: ToolDefinition -): ToolDefinition => definition +): ToolDefinition => ({ + ...definition, + async execute(input, context) { + if (context.abort?.aborted) { + const message = "the request was cancelled; nothing was changed" + return { + title: "cancelled", + output: `Error: ${message}`, + metadata: { error: true, message } + } + } + return definition.execute(input, context) + } +}) -/** - * Run an Effect from a tool executor while preserving typed failures. - * - * `Effect.runPromiseExit` preserves the typed failure, so permission errors - * can be rethrown as the V2 host expects. - */ export const runToolEffect = async ( effect: Effect.Effect ): Promise => { @@ -83,11 +80,6 @@ export const runToolEffect = async ( throw Cause.squash(exit.cause) } -/** - * V2 permission.assert rejections must propagate to the host instead of being - * converted into normal tool output. When the permission service preserved the - * original host error, rethrow that; otherwise rethrow the tagged error. - */ export const rethrowPermissionDenied = (error: unknown): void => { if (error instanceof PermissionDeniedError) { throw error.cause === undefined ? error : error.cause diff --git a/src/tools/_readPermission.ts b/src/tools/_readPermission.ts index 02eb713..817afb3 100644 --- a/src/tools/_readPermission.ts +++ b/src/tools/_readPermission.ts @@ -3,12 +3,6 @@ import type { ToolContext } from "../tool.js" import { PermissionDeniedError } from "../domain/errors.js" import { permissionAliases } from "../services/PermissionService.js" -/** - * Custom V2 tools are not automatically covered by the host's native `read` - * action. Ask explicitly before handing notebook content to a read-only tool. - * The lexical and resolved paths are both requested so a symlink alias cannot - * bypass a deny rule on the real notebook. - */ export const assertReadPermission = async ( context: ToolContext, filePath: string diff --git a/src/tools/_resolveOptions.ts b/src/tools/_resolveOptions.ts index 0334645..c458cf5 100644 --- a/src/tools/_resolveOptions.ts +++ b/src/tools/_resolveOptions.ts @@ -1,8 +1,5 @@ import type { ToolContext } from "../tool.js" import { resolveOptionsFromEnv } from "../services/index.js" -// Thin re-export so tools/ can use the same resolver as services/. -// Keeping the implementation in services/index.ts ensures both layers -// agree on env handling and fallback semantics. export const resolveToolOptions = (context?: ToolContext) => resolveOptionsFromEnv(context?.pluginOptions) diff --git a/src/tools/cell_delete.ts b/src/tools/cell_delete.ts index 78b7f3e..6ac0974 100644 --- a/src/tools/cell_delete.ts +++ b/src/tools/cell_delete.ts @@ -21,9 +21,8 @@ export const ipynbCellDeleteTool = tool({ "Delete a cell from a Jupyter Notebook by index. Asks permission before writing. Returns the deleted cell's type, a short preview of its source, and the new total cell count.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { - // The result includes a preview of the deleted source. await assertReadPermission(context, input.filePath) const result = await runToolEffect( services.edit.deleteCell(input.filePath, input.cellIndex) @@ -46,7 +45,9 @@ export const ipynbCellDeleteTool = tool({ filePath: result.absPath, deletedIndex: result.deletedIndex, deletedType: result.deletedType, - totalCells: result.totalCells + totalCells: result.totalCells, + writeMode: result.writeMode, + writeModeReason: result.writeModeReason } } } catch (err) { diff --git a/src/tools/cell_insert.ts b/src/tools/cell_insert.ts index bb7fc18..6645e99 100644 --- a/src/tools/cell_insert.ts +++ b/src/tools/cell_insert.ts @@ -4,6 +4,7 @@ import { z } from "zod" import { rethrowPermissionDenied, runToolEffect, tool } from "../tool.js" import type { ToolContext } from "../tool.js" import { buildServices } from "../services/index.js" +import { assertReadPermission } from "./_readPermission.js" import { errorToMessage } from "../domain/errors.js" const args = { @@ -27,8 +28,9 @@ export const ipynbCellInsertTool = tool({ "Insert a new cell into a Jupyter Notebook at the given index, or append to the end when index is omitted. The new cell starts with empty metadata; code cells also start with execution_count=null and outputs=[]. Asks permission before writing. Returns the new cell's index and the new total cell count.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { + await assertReadPermission(context, input.filePath) const result = await runToolEffect( services.edit.insertCell( input.filePath, @@ -56,7 +58,9 @@ export const ipynbCellInsertTool = tool({ filePath: result.absPath, cellIndex: result.cellIndex, cellType: result.cellType, - totalCells: result.totalCells + totalCells: result.totalCells, + writeMode: result.writeMode, + writeModeReason: result.writeModeReason } } } catch (err) { diff --git a/src/tools/cell_move.ts b/src/tools/cell_move.ts index 105dd54..18095e7 100644 --- a/src/tools/cell_move.ts +++ b/src/tools/cell_move.ts @@ -26,7 +26,7 @@ export const ipynbCellMoveTool = tool({ "Move a cell within a Jupyter Notebook from one index to another. Asks permission before writing. Returns the original and final index plus the (unchanged) total cell count.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { const result = await runToolEffect( services.edit.moveCell( @@ -48,7 +48,9 @@ export const ipynbCellMoveTool = tool({ fromIndex: result.fromIndex, toIndex: result.toIndex, cellType: result.cellType, - totalCells: result.totalCells + totalCells: result.totalCells, + writeMode: result.writeMode, + writeModeReason: result.writeModeReason } } } catch (err) { diff --git a/src/tools/clean.ts b/src/tools/clean.ts index 0db93f0..094e8f2 100644 --- a/src/tools/clean.ts +++ b/src/tools/clean.ts @@ -3,6 +3,7 @@ import { z } from "zod" import { rethrowPermissionDenied, runToolEffect, tool } from "../tool.js" import type { ToolContext } from "../tool.js" import { buildServices } from "../services/index.js" +import { assertReadPermission } from "./_readPermission.js" import { errorToMessage } from "../domain/errors.js" const args = { @@ -35,8 +36,9 @@ export const ipynbCleanTool = tool({ "Clean a Jupyter Notebook for Git/review by clearing outputs, execution counts, and widget state. Validates the notebook before and after, asks permission before writing, and returns a summary of what was changed.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { + await assertReadPermission(context, input.filePath) const result = await runToolEffect( services.clean.clean(input.filePath, { clearOutputs: input.clearOutputs, @@ -53,6 +55,7 @@ export const ipynbCleanTool = tool({ lines.push(`Removed execution_count: ${result.removedExecutionCounts}`) lines.push(`Removed widget state entries: ${result.removedWidgets}`) lines.push(`Removed large images: ${result.removedImages}`) + lines.push(`Normalized source arrays: ${result.normalizedSources}`) return { title: `Clean ${input.filePath}`, output: lines.join("\n"), @@ -62,7 +65,10 @@ export const ipynbCleanTool = tool({ removedOutputs: result.removedOutputs, removedExecutionCounts: result.removedExecutionCounts, removedWidgets: result.removedWidgets, - removedImages: result.removedImages + removedImages: result.removedImages, + normalizedSources: result.normalizedSources, + writeMode: result.writeMode, + writeModeReason: result.writeModeReason } } } catch (err) { diff --git a/src/tools/doctor.ts b/src/tools/doctor.ts index 83e8d46..032af98 100644 --- a/src/tools/doctor.ts +++ b/src/tools/doctor.ts @@ -24,7 +24,7 @@ export const ipynbDoctorTool = tool({ "Diagnose the opencode-ipynb environment: which Python interpreter was found, where the helper lives, which Jupyter dependencies are available, and how to fix anything that is missing. Never installs anything.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { if (services.pythonPathError !== undefined) { const message = `Invalid pythonPath: ${services.pythonPathError}` @@ -68,6 +68,18 @@ export const ipynbDoctorTool = tool({ const lines: string[] = [] lines.push("# opencode-ipynb doctor") lines.push("") + if (services.envOptionsError !== undefined) { + lines.push("## Plugin options") + lines.push( + `- [warning] OPENCODE_IPYNB_OPTIONS is set but invalid: ${sanitizeInline( + services.envOptionsError + )}` + ) + lines.push( + "- instance or default options are in effect; fix the environment variable to use it" + ) + lines.push("") + } lines.push("## Python interpreter") if (doctor.selected) { lines.push( diff --git a/src/tools/edit.ts b/src/tools/edit.ts index ca929c3..94ada01 100644 --- a/src/tools/edit.ts +++ b/src/tools/edit.ts @@ -3,6 +3,7 @@ import { z } from "zod" import { rethrowPermissionDenied, runToolEffect, tool } from "../tool.js" import type { ToolContext } from "../tool.js" import { buildServices } from "../services/index.js" +import { assertReadPermission } from "./_readPermission.js" import { errorToMessage } from "../domain/errors.js" const args = { @@ -23,8 +24,9 @@ export const ipynbEditTool = tool({ "Edit a single cell of a Jupyter Notebook safely (cellIndex is 0-based). Validates before and after, preserves metadata, asks permission before writing, and returns a concise confirmation. For code cells, the default 'auto' mode clears outputs and execution_count when the source changes.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { + await assertReadPermission(context, input.filePath) const result = await runToolEffect( services.edit.editCell(input.filePath, { cellIndex: input.cellIndex, @@ -41,7 +43,9 @@ export const ipynbEditTool = tool({ cellIndex: result.cellIndex, cellType: result.cellType, clearedOutputs: result.clearedOutputs, - changed: result.changed + changed: result.changed, + writeMode: result.writeMode, + writeModeReason: result.writeModeReason } } } catch (err) { diff --git a/src/tools/export.ts b/src/tools/export.ts index 0d7c534..32ffe97 100644 --- a/src/tools/export.ts +++ b/src/tools/export.ts @@ -21,7 +21,9 @@ const args = { outputPath: z .string() .optional() - .describe("Optional path to write the export to. If omitted, returns content in the tool output."), + .describe( + "Optional path to write the export to (.md, .markdown, .py, .txt or .rst); any other extension is refused so an export cannot overwrite configuration or key material. If omitted, returns content in the tool output." + ), maxExportChars: z .number() .int() @@ -36,7 +38,7 @@ export const ipynbExportTool = tool({ "Export a Jupyter Notebook to markdown, python, or a textual summary. Optionally write the result to a file (after permission).", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { await assertReadPermission(context, input.filePath) const result = await runToolEffect( diff --git a/src/tools/inspect.ts b/src/tools/inspect.ts index db35e28..a5994d8 100644 --- a/src/tools/inspect.ts +++ b/src/tools/inspect.ts @@ -102,7 +102,7 @@ export const ipynbInspectTool = tool({ "Inspect a Jupyter Notebook (.ipynb) and return a compact summary (kernel, language, cell counts, output/error/large-output stats, cell table) without dumping the full JSON.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { await assertReadPermission(context, input.filePath) if ( diff --git a/src/tools/kernel.ts b/src/tools/kernel.ts index a29b272..a0fca35 100644 --- a/src/tools/kernel.ts +++ b/src/tools/kernel.ts @@ -152,7 +152,7 @@ export const ipynbKernelTool = tool({ "Inspect and manage the long-lived (warm) Python kernels used by ipynb_run when the `warmKernel` plugin option is set. Use 'status' to see whether the feature is on, 'list' to see the live kernels, 'restart' to stop the current kernel (the next run starts a new one), and 'shutdown' to release a kernel. When the warm kernel is disabled, this tool returns a clear message — the rest of the plugin is unaffected.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { const result = await runToolEffect(run(services, input, context)) return { diff --git a/src/tools/lsp.ts b/src/tools/lsp.ts index 492ac29..8330d11 100644 --- a/src/tools/lsp.ts +++ b/src/tools/lsp.ts @@ -127,7 +127,8 @@ export const ipynbLspTool = tool({ } const materialized = await materializeVirtualDocument( document, - context.directory + context.directory, + context.warningSink === undefined ? undefined : { warningSink: context.warningSink } ) const lines = [ `Virtual Python document: ${sanitizeInline(materialized.path)}`, @@ -162,7 +163,11 @@ export const ipynbLspTool = tool({ metadata: { filePath: absolute, virtualPath: materialized.path, - cells: materialized.cells.slice(0, 1_000) + cells: materialized.cells.slice(0, 1_000), + ...(materialized.warnings === undefined || + materialized.warnings.length === 0 + ? {} + : { notebookWarnings: materialized.warnings }) } } } @@ -188,7 +193,8 @@ export const ipynbLspTool = tool({ !(await isPyrightAvailable( pluginOpts.pyrightPath, pluginOpts.diagnosticsTimeoutMs, - context.abort + context.abort, + context.warningSink === undefined ? undefined : { warningSink: context.warningSink } )) ) { return { @@ -232,6 +238,9 @@ export const ipynbLspTool = tool({ displayPath: input.filePath, tempFilePath: tempFile, ownedTempFile: true, + ...(context.warningSink === undefined + ? {} + : { warningSink: context.warningSink }), requestFallbackPermission: async () => { try { await context.ask({ @@ -268,7 +277,9 @@ export const ipynbLspTool = tool({ ? "pyright analyzed zero files. Its configuration likely excludes this sidecar; adjust `exclude`/`include` so diagnostics are meaningful." : result.skipped === "temp-unwritable" ? "Neither the notebook directory nor the system temp directory is writable for the diagnostics temp file." - : "Diagnostics failed (pyright returned invalid output or could not run); no conclusion was reached." + : result.skipped === "unsafe-shell-command" + ? "Diagnostics were skipped: the pyright command or one of its arguments contains characters a shell would reinterpret (for example % or &). Rename pyright, or the notebook directory, so the command line is free of shell metacharacters." + : "Diagnostics failed (pyright returned invalid output or could not run); no conclusion was reached." return { title: `ipynb_lsp ${input.filePath}`, output: message, @@ -300,6 +311,7 @@ export const ipynbLspTool = tool({ metadata: { filePath: absolute, notebookDiagnostics: capDiagnosticMetadata(result.diagnostics), + ...(result.warnings === undefined ? {} : { warnings: result.warnings }), ...(result.skipped === undefined ? {} : { skipped: result.skipped }) } } diff --git a/src/tools/outputs.ts b/src/tools/outputs.ts index 833d309..eae0c64 100644 --- a/src/tools/outputs.ts +++ b/src/tools/outputs.ts @@ -53,7 +53,7 @@ export const ipynbOutputsTool = tool({ "Work with cell outputs: list (with pagination), read (per-cell), read_error, clear_cell, clear_all (cellIndex is 0-based). Always asks permission before clearing. Images and base64 payloads are omitted by default.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { if (input.operation !== "clear_cell" && input.operation !== "clear_all") { await assertReadPermission(context, input.filePath) diff --git a/src/tools/read.ts b/src/tools/read.ts index f0c650c..78c444c 100644 --- a/src/tools/read.ts +++ b/src/tools/read.ts @@ -59,7 +59,6 @@ const readArgsSchema = z.object(args).superRefine((input, ctx) => { return } if (hasCell) return - // Range mode: both start and end must be present and start <= end. if (!hasStart || !hasEnd) { ctx.addIssue({ code: z.ZodIssueCode.custom, @@ -94,14 +93,12 @@ export const ipynbReadTool = tool({ } } const input = parsed.data - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { await assertReadPermission(context, input.filePath) const pluginOpts = resolveToolOptions(context) const requestOptions = { ...input, - // Requesting images implies reading outputs; otherwise there is - // nothing to attach. includeOutputs: input.includeOutputs || input.includeImages, saveImages: input.includeImages, maxOutputChars: input.maxOutputChars ?? pluginOpts.defaultMaxOutputChars diff --git a/src/tools/repro.ts b/src/tools/repro.ts index 538e833..4dcdff1 100644 --- a/src/tools/repro.ts +++ b/src/tools/repro.ts @@ -348,7 +348,7 @@ export const ipynbReproTool = tool({ "Reproducibility report for a Jupyter Notebook: kernel + language (from kernelspec / language_info), Python interpreter version + executable + platform, top 50 lines of `pip freeze --local` (requires shell permission), and a static analysis of the notebook for things that hurt reproducibility (long source, non-deterministic patterns, missing packages, filesystem reads, random seeds). Does NOT execute notebook cells. Falls back to a partial report (warnings only) if Python is not on PATH.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) try { if (services.pythonPathError !== undefined) { const message = `Invalid pythonPath: ${services.pythonPathError}` diff --git a/src/tools/run.ts b/src/tools/run.ts index c9faaff..97e9967 100644 --- a/src/tools/run.ts +++ b/src/tools/run.ts @@ -26,7 +26,9 @@ const args = { .int() .positive() .optional() - .describe("Timeout in milliseconds (default 120000, from plugin options)"), + .describe( + "Timeout in milliseconds for each executed cell (default 120000, from plugin options). A request is aborted once it exceeds twice this budget plus five seconds, so a multi-cell run should keep its total work within that window." + ), save: z.boolean().optional().default(true).describe("Persist outputs to the notebook (default: true)"), workingDirectory: z.string().optional().describe("Working directory for the one-shot Python runner (not supported with warmKernel)"), maxOutputChars: z @@ -42,7 +44,7 @@ export const ipynbRunTool = tool({ "Execute a cell, range, or full notebook via the Python helper (nbclient; cellIndex is 0-based). The plugin never installs Python dependencies; it only detects them and returns a clear error if anything is missing. Use ipynb_doctor first if you are unsure about the environment.", args, async execute(input: z.infer>, context: ToolContext) { - const services = buildServices(context) + const services = buildServices(context, { warningSink: context.warningSink }) const pluginOpts = resolveToolOptions(context) const maxOutputChars = input.maxOutputChars ?? pluginOpts.defaultMaxOutputChars const timeoutMs = input.timeoutMs ?? pluginOpts.defaultTimeoutMs @@ -116,7 +118,9 @@ export const ipynbRunTool = tool({ filePath: result.absPath, executedCells: result.executedCells.slice(0, 1_000), durationMs: result.durationMs, - saved: result.saved + saved: result.saved, + writeMode: result.writeMode, + writeModeReason: result.writeModeReason } } } catch (err) { diff --git a/src/utils/ansi.ts b/src/utils/ansi.ts index 3b851ec..502d884 100644 --- a/src/utils/ansi.ts +++ b/src/utils/ansi.ts @@ -1,18 +1,45 @@ const ANSI_PATTERN = /\u001b\[[0-9;?]*[ -/]*[@-~]/g +const ANSI_TEST_PATTERN = /\u001b\[[0-9;?]*[ -/]*[@-~]/ const CARRIAGE_RETURN_PATTERN = /\r/g +const OSC_MAX_BODY = 256 + +const terminatorEnd = (text: string, from: number, limit: number): number => { + for (let index = from; index <= limit; index += 1) { + const code = text.charCodeAt(index) + if (code === 0x07) return index + 1 + if (code === 0x1b && text.charCodeAt(index + 1) === 0x5c) return index + 2 + } + return -1 +} + +const stripOscSequences = (text: string): string => { + let result = "" + let cursor = 0 + let start = text.indexOf("\u001b]") + while (start >= 0) { + const bodyStart = start + 2 + const limit = Math.min(text.length - 1, bodyStart + OSC_MAX_BODY) + const end = terminatorEnd(text, bodyStart, limit) + if (end < 0) { + // No terminator inside the window: skip the whole examined body so the + // next introducer search starts past it instead of one char later. + start = text.indexOf("\u001b]", limit + 1) + continue + } + result += text.slice(cursor, start) + cursor = end + start = text.indexOf("\u001b]", cursor) + } + return cursor === 0 ? text : result + text.slice(cursor) +} export const stripAnsi = (text: string): string => text.replace(ANSI_PATTERN, "").replace(CARRIAGE_RETURN_PATTERN, "") -/** Remove terminal control sequences/bytes while keeping newlines and tabs. */ export const sanitizeTerminal = (text: string): string => - text - .replace(/\r\n?/g, "\n") - // Bound the OSC payload: an unterminated introducer must not scan the - // whole (up to 50 MB) notebook for every occurrence. - .replace(/\u001b\][^\u0007]{0,256}(?:\u0007|\u001b\\)/g, "") + stripOscSequences(text.replace(/\r\n?/g, "\n")) .replace(/\u001b\[[0-9;?]*[ -/]*[@-~]/g, "") .replace(/\u001b[@-_]/g, "") .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "") -export const hasAnsi = (text: string): boolean => ANSI_PATTERN.test(text) +export const hasAnsi = (text: string): boolean => ANSI_TEST_PATTERN.test(text) diff --git a/src/utils/atomic-replace.ts b/src/utils/atomic-replace.ts index 0b5b0e0..894e965 100644 --- a/src/utils/atomic-replace.ts +++ b/src/utils/atomic-replace.ts @@ -1,36 +1,56 @@ import { promises as fsp } from "node:fs" import { randomBytes } from "node:crypto" +import { type WarningSink, warningFrom } from "./warnings.js" -/** - * Rename `temp` over `target`. On Windows rename fails when the target - * exists; move the original to a backup first and restore it if the second - * rename fails, so a failed replace never deletes the only copy. - */ export const replaceFile = async ( temp: string, - target: string + target: string, + sink?: WarningSink ): Promise => { try { await fsp.rename(temp, target) return } catch (error) { if (process.platform !== "win32") throw error + const targetStat = await fsp.lstat(target).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code !== "ENOENT") { + sink?.add(warningFrom("atomic-replace", error, `inspecting ${target}`)) + } + return undefined + }) + if (targetStat?.isDirectory()) throw error const backup = `${target}.${process.pid}.${randomBytes(4).toString("hex")}.bak` let backedUp = false try { await fsp.rename(target, backup) backedUp = true - } catch { - // Target did not exist or could not be moved. + } catch (moveError) { + sink?.add(warningFrom("atomic-replace", moveError, "backup before replace")) } try { await fsp.rename(temp, target) } catch (second) { if (backedUp) { - await fsp.rename(backup, target).catch(() => {}) + try { + await fsp.rename(backup, target) + } catch (restoreError) { + sink?.add( + warningFrom( + "atomic-replace", + restoreError, + `restore failed, original kept at ${backup}` + ) + ) + } } throw second } - if (backedUp) await fsp.rm(backup, { force: true }).catch(() => {}) + if (backedUp) { + try { + await fsp.rm(backup, { force: true }) + } catch (cleanupError) { + sink?.add(warningFrom("atomic-replace", cleanupError, `left ${backup}`)) + } + } } } diff --git a/src/utils/attachments.ts b/src/utils/attachments.ts index 3645676..4604513 100644 --- a/src/utils/attachments.ts +++ b/src/utils/attachments.ts @@ -20,7 +20,6 @@ export const formatAttachment = ( filename?: string ): ToolAttachment => { const ext = pickExtensionForMime(mime) - // Jupyter stores image/svg+xml as raw XML, unlike base64 raster formats. const isRawSvg = mime.toLowerCase() === "image/svg+xml" && (payload.includes(" => { @@ -17,8 +16,6 @@ export const analyzeExecutionOrder = ( if (!cell || cell.cell_type !== "code") continue const ec = cell.execution_count if (ec === null || ec === undefined) { - // A null count is a fresh-run boundary: subsequent cells compare - // against the new starting count, not the last non-null one. lastCount = null continue } diff --git a/src/utils/fence.ts b/src/utils/fence.ts index 58b1191..b7cbfcb 100644 --- a/src/utils/fence.ts +++ b/src/utils/fence.ts @@ -1,4 +1,3 @@ -/** Fence long enough that backticks inside the content cannot close it. */ export const codeFence = (text: string): string => { const runs = text.match(/`+/g) ?? [] const longest = runs.reduce((max, run) => Math.max(max, run.length), 0) diff --git a/src/utils/imports.ts b/src/utils/imports.ts index 825443a..6d66fad 100644 --- a/src/utils/imports.ts +++ b/src/utils/imports.ts @@ -27,16 +27,8 @@ const stripComment = (line: string): string => line.replace(/#.*$/, "") const TRIPLE_DOUBLE = /"""[\s\S]*?"""/g const TRIPLE_SINGLE = /'''[\s\S]*?'''/g -/** - * Extract the top-level modules imported by Python source. For - * `from pandas import DataFrame` the module is `pandas`, not `DataFrame`. - * This is intentionally a lightweight parser (not a Python AST); it handles - * aliases, comments, dotted modules, and parenthesized from-imports. - */ export const extractImportNames = (source: string): string[] => { const names: string[] = [] - // Strip triple-quoted bodies first; the line parser below never scans past - // a single line, so blank/whitespace-heavy notebooks stay linear. const withoutCommentLines = source.replace(/^[ \t]*#[^\n]*$/gm, "") const withoutStrings = withoutCommentLines .replace(TRIPLE_DOUBLE, "") diff --git a/src/utils/json-patch.ts b/src/utils/json-patch.ts new file mode 100644 index 0000000..521bbd1 --- /dev/null +++ b/src/utils/json-patch.ts @@ -0,0 +1,813 @@ +export interface JsonTextStyle { + readonly newline: "\n" | "\r\n" + readonly itemSeparator: string + readonly keySeparator: string + readonly ensureAscii: boolean + readonly unit: string +} + +interface LiteralNode { + readonly kind: "literal" + readonly start: number + readonly end: number + readonly value: unknown +} + +interface ItemSpan { + readonly start: number + readonly end: number +} + +interface ArrayNode { + readonly kind: "array" + readonly start: number + readonly end: number + readonly items: ReadonlyArray + readonly value: ReadonlyArray +} + +interface ObjectEntry { + readonly key: string + readonly keyStart: number + readonly value: JsonNode +} + +interface ObjectNode { + readonly kind: "object" + readonly start: number + readonly end: number + readonly entries: ReadonlyArray + readonly value: Record +} + +export type JsonNode = LiteralNode | ArrayNode | ObjectNode + +const NUMBER = /-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?/y + +const isWhitespace = (code: number): boolean => + code === 0x20 || code === 0x09 || code === 0x0a || code === 0x0d + +const skipWhitespace = (text: string, from: number): number => { + let pos = from + while (pos < text.length && isWhitespace(text.charCodeAt(pos))) pos += 1 + return pos +} + +const parseStringSpan = (text: string, start: number): number => { + let pos = start + 1 + while (pos < text.length) { + const char = text[pos] + if (char === "\\") { + pos += 2 + continue + } + if (char === '"') return pos + 1 + pos += 1 + } + throw new SyntaxError("unterminated string") +} + +export const MAX_JSON_DEPTH = 512 + +class DepthExceededError extends RangeError {} + +const skipScalar = (text: string, from: number): number => { + const char = text[from] + if (char === '"') return parseStringSpan(text, from) + for (const literal of ["true", "false", "null"] as const) { + if (text.startsWith(literal, from)) return from + literal.length + } + NUMBER.lastIndex = from + const match = NUMBER.exec(text) + if (match !== null) return from + match[0].length + throw new SyntaxError(`unexpected token at ${from}`) +} + +const skipValue = (text: string, from: number, depth = 0): number => { + if (depth > MAX_JSON_DEPTH) { + throw new DepthExceededError( + `notebook nesting exceeds the supported depth of ${MAX_JSON_DEPTH}` + ) + } + const start = skipWhitespace(text, from) + const char = text[start] + if (char !== "{" && char !== "[") return skipScalar(text, start) + const close = char === "{" ? "}" : "]" + let pos = skipWhitespace(text, start + 1) + if (text[pos] === close) return pos + 1 + for (;;) { + if (char === "{") { + const keyEnd = parseStringSpan(text, skipWhitespace(text, pos)) + pos = skipWhitespace(text, keyEnd) + pos = skipWhitespace(text, pos + 1) + } + pos = skipWhitespace(text, skipValue(text, pos, depth + 1)) + if (text[pos] === ",") { + pos = skipWhitespace(text, pos + 1) + continue + } + if (text[pos] === close) return pos + 1 + throw new SyntaxError(`expected , or ${close}`) + } +} + +const parseNode = ( + text: string, + from: number, + depth = 0, + known?: unknown +): JsonNode => { + if (depth > MAX_JSON_DEPTH) { + throw new DepthExceededError( + `notebook nesting exceeds the supported depth of ${MAX_JSON_DEPTH}` + ) + } + const start = skipWhitespace(text, from) + const char = text[start] + if (char === '"') { + const end = parseStringSpan(text, start) + return { kind: "literal", start, end, value: known } + } + if (char === "{") { + const entries: ObjectEntry[] = [] + let pos = skipWhitespace(text, start + 1) + if (text[pos] === "}") { + return { + kind: "object", + start, + end: pos + 1, + entries, + value: (known ?? {}) as Record + } + } + for (;;) { + const keyStart = skipWhitespace(text, pos) + const keyEnd = parseStringSpan(text, keyStart) + const rawKey = text.slice(keyStart + 1, keyEnd - 1) + const key = rawKey.indexOf("\\") === -1 ? rawKey : (JSON.parse(text.slice(keyStart, keyEnd)) as string) + pos = skipWhitespace(text, keyEnd) + pos = skipWhitespace(text, pos + 1) + const childKnown = + typeof known === "object" && known !== null && !Array.isArray(known) + ? (known as Record)[key] + : undefined + const value = parseNode(text, pos, depth + 1, childKnown) + entries.push({ key, keyStart, value }) + pos = skipWhitespace(text, value.end) + if (text[pos] === ",") { + pos += 1 + continue + } + if (text[pos] === "}") { + return { + kind: "object", + start, + end: pos + 1, + entries, + value: (known ?? {}) as Record + } + } + throw new SyntaxError("expected , or } in object") + } + } + if (char === "[") { + const items: ItemSpan[] = [] + let pos = skipWhitespace(text, start + 1) + if (text[pos] === "]") { + return { + kind: "array", + start, + end: pos + 1, + items, + value: (known ?? []) as ReadonlyArray + } + } + for (;;) { + const valueStart = skipWhitespace(text, pos) + const valueEnd = skipValue(text, valueStart, depth + 1) + items.push({ start: valueStart, end: valueEnd }) + pos = skipWhitespace(text, valueEnd) + if (text[pos] === ",") { + pos += 1 + continue + } + if (text[pos] === "]") { + return { + kind: "array", + start, + end: pos + 1, + items, + value: (known ?? []) as ReadonlyArray + } + } + throw new SyntaxError("expected , or ] in array") + } + } + for (const literal of ["true", "false", "null"] as const) { + if (text.startsWith(literal, start)) { + return { kind: "literal", start, end: start + literal.length, value: known } + } + } + NUMBER.lastIndex = start + const match = NUMBER.exec(text) + if (match !== null) { + return { kind: "literal", start, end: start + match[0].length, value: known } + } + throw new SyntaxError(`unexpected token at ${start}`) +} + +export const jsonEqual = (left: unknown, right: unknown): boolean => { + if (left === right) return true + if (left === null || right === null) return false + if (typeof left !== typeof right) return false + const leftIsArray = Array.isArray(left) + if (leftIsArray !== Array.isArray(right)) return false + if (leftIsArray) { + const a = left as ReadonlyArray + const b = right as ReadonlyArray + if (a.length !== b.length) return false + return a.every((item, index) => jsonEqual(item, b[index])) + } + if (typeof left === "object") { + const leftKeys = Object.keys(left as object) + const rightKeys = Object.keys(right as object) + if (leftKeys.length !== rightKeys.length) return false + return leftKeys.every( + (key) => + Object.prototype.hasOwnProperty.call(right, key) && + jsonEqual( + (left as Record)[key], + (right as Record)[key] + ) + ) + } + return false +} + +const canonicalJson = (value: unknown): string => { + if (value === null || typeof value !== "object") return JSON.stringify(value) ?? "null" + if (Array.isArray(value)) return `[${value.map(canonicalJson).join(",")}]` + const record = value as Record + return `{${Object.keys(record) + .sort() + .map((key) => `${JSON.stringify(key)}:${canonicalJson(record[key])}`) + .join(",")}}` +} + +const ESCAPE_WINDOW = 4096 + +const HEX = Array.from({ length: 0x10000 }, (_, code) => + code < 0x7f ? undefined : `\\u${code.toString(16).padStart(4, "0")}` +) + +const escapeWindow = (chunk: string): string => { + const parts: string[] = [] + let start = 0 + for (let index = 0; index < chunk.length; index += 1) { + const replacement = HEX[chunk.charCodeAt(index)] + if (replacement === undefined) continue + if (start < index) parts.push(chunk.slice(start, index)) + parts.push(replacement) + start = index + 1 + } + if (start === 0) return chunk + parts.push(chunk.slice(start)) + return parts.join("") +} + +const NON_ASCII = /[\u007f-\uffff]/ + +const MAX_ESCAPED_STRING = 64 * 1024 * 1024 + +const encodeString = (value: string, ensureAscii: boolean): string => { + const json = JSON.stringify(value) + if (!ensureAscii || !NON_ASCII.test(json)) return json + if (json.length > MAX_ESCAPED_STRING) { + throw new RangeError( + `string escaping would exceed the supported size of ${MAX_ESCAPED_STRING} characters` + ) + } + const parts: string[] = [] + for (let offset = 0; offset < json.length; offset += ESCAPE_WINDOW) { + const chunk = json.slice(offset, offset + ESCAPE_WINDOW) + parts.push(NON_ASCII.test(chunk) ? escapeWindow(chunk) : chunk) + } + return parts.join("") +} + +const lineStart = (text: string, pos: number): number => { + let index = pos + while (index > 0 && text[index - 1] !== "\n") index -= 1 + return index +} + +const indentAt = (text: string, pos: number): string => { + const start = lineStart(text, pos) + const prefix = text.slice(start, pos) + return /^[ \t]*$/.test(prefix) ? prefix : "" +} + +const newlineWithin = (text: string, from: number, to: number): boolean => { + for (let index = from; index < to; index += 1) { + if (text.charCodeAt(index) === 10) return true + } + return false +} + +const isMultiline = (text: string, node: JsonNode): boolean => + newlineWithin(text, node.start, node.end) + +interface Layout { + readonly text: string + readonly style: JsonTextStyle +} + +const childIndentForArray = (layout: Layout, node: ArrayNode): string => { + const first = node.items[0] + if (first === undefined || !isMultiline(layout.text, node)) return "" + return indentAt(layout.text, first.start) +} + +const childIndentForObject = (layout: Layout, node: ObjectNode): string => { + const first = node.entries[0] + if (first === undefined || !isMultiline(layout.text, node)) return "" + return indentAt(layout.text, first.keyStart) +} + +const formatValue = ( + value: unknown, + indent: string, + multiline: boolean, + layout: Layout +): string => { + const { style } = layout + const childIndent = `${indent}${style.unit}` + const separator = multiline ? `,${style.newline}` : style.itemSeparator + if (value === null) return "null" + if (typeof value === "number") { + return Number.isFinite(value) ? JSON.stringify(value) : "null" + } + if (typeof value === "boolean") return String(value) + if (typeof value === "string") return encodeString(value, style.ensureAscii) + if (Array.isArray(value)) { + if (value.length === 0) return "[]" + if (!multiline) { + return `[${value + .map((item) => formatValue(item, childIndent, false, layout)) + .join(style.itemSeparator)}]` + } + return `[${style.newline}${value + .map((item) => `${childIndent}${formatValue(item, childIndent, true, layout)}`) + .join(separator)}${style.newline}${indent}]` + } + const record = value as Record + const keys = Object.keys(record) + if (keys.length === 0) return "{}" + if (!multiline) { + return `{${keys + .map( + (key) => + `${encodeString(key, style.ensureAscii)}${style.keySeparator}${formatValue( + record[key], + childIndent, + false, + layout + )}` + ) + .join(style.itemSeparator)}}` + } + return `{${style.newline}${keys + .map( + (key) => + `${childIndent}${encodeString(key, style.ensureAscii)}${ + style.keySeparator + }${formatValue(record[key], childIndent, true, layout)}` + ) + .join(separator)}${style.newline}${indent}}` +} + +interface Edit { + readonly start: number + readonly end: number + readonly text: string +} + +const prefixLength = ( + left: ReadonlyArray, + right: ReadonlyArray +): number => { + let index = 0 + while ( + index < left.length && + index < right.length && + jsonEqual(left[index], right[index]) + ) { + index += 1 + } + return index +} + +const suffixLength = ( + left: ReadonlyArray, + right: ReadonlyArray, + prefix: number +): number => { + let count = 0 + while ( + count < left.length - prefix && + count < right.length - prefix && + jsonEqual(left[left.length - 1 - count], right[right.length - 1 - count]) + ) { + count += 1 + } + return count +} + + +const patchArray = ( + value: ReadonlyArray, + node: ArrayNode, + edits: Edit[], + layout: Layout, + indent: string +): void => { + const multiline = isMultiline(layout.text, node) + const oldItems = node.value + const nodeAt = (index: number): JsonNode => { + const span = node.items[index]! + return parseNode(layout.text, span.start, 0, oldItems[index]) + } + const prefix = prefixLength(oldItems, value) + const suffix = suffixLength(oldItems, value, prefix) + const oldMiddle = node.items.slice(prefix, node.items.length - suffix) + const newMiddle = value.slice(prefix, value.length - suffix) + const childIndent = childIndentForArray(layout, node) || `${indent}${layout.style.unit}` + const fileMultiline = multiline || node.items.length === 0 + const separator = fileMultiline + ? `,${layout.style.newline}${childIndent}` + : layout.style.itemSeparator + + let rawByKey: Map | undefined + const rawIndex = (): Map => { + if (rawByKey === undefined) { + rawByKey = new Map() + for (let index = 0; index < node.items.length; index += 1) { + const source = node.items[index]! + rawByKey.set( + canonicalJson(oldItems[index]), + layout.text.slice(source.start, source.end) + ) + } + } + return rawByKey + } + const rawFor = (item: unknown): string | undefined => { + const raw = rawIndex().get(canonicalJson(item)) + if (raw === undefined) return undefined + return raw.includes("\n") && !fileMultiline ? undefined : raw + } + + if (oldMiddle.length > 0 && newMiddle.length === oldMiddle.length) { + const reordered = + oldMiddle.length > 1 && + !oldMiddle.every((item, i) => jsonEqual(item, newMiddle[i])) + if (reordered) { + edits.push({ + start: oldMiddle[0]!.start, + end: oldMiddle[oldMiddle.length - 1]!.end, + text: newMiddle + .map((item) => rawFor(item) ?? formatValue(item, childIndent, fileMultiline, layout)) + .join(separator) + }) + return + } + for (let i = 0; i < oldMiddle.length; i += 1) { + patchNode( + newMiddle[i], + oldItems[prefix + i], + nodeAt(prefix + i), + edits, + layout, + childIndent + ) + } + return + } + const emitItem = (item: unknown): string => + rawFor(item) ?? formatValue(item, childIndent, fileMultiline, layout) + + if (oldMiddle.length > 0 && newMiddle.length > 0) { + edits.push({ + start: oldMiddle[0]!.start, + end: oldMiddle[oldMiddle.length - 1]!.end, + text: newMiddle + .map((item) => emitItem(item)) + .join(separator) + }) + return + } + if (oldMiddle.length > 0) { + if (newMiddle.length === 0 && prefix === 0 && suffix === 0) { + edits.push({ start: node.start, end: node.end, text: "[]" }) + return + } + if (prefix > 0) { + edits.push({ + start: node.items[prefix - 1]!.end, + end: oldMiddle[oldMiddle.length - 1]!.end, + text: "" + }) + } else { + edits.push({ + start: oldMiddle[0]!.start, + end: node.items[oldMiddle.length]!.start, + text: "" + }) + } + return + } + if (newMiddle.length > 0) { + const text = newMiddle.map((item) => emitItem(item)).join(separator) + if (prefix > 0) { + edits.push({ + start: node.items[prefix - 1]!.end, + end: node.items[prefix - 1]!.end, + text: `${separator}${text}` + }) + } else if (node.items.length > 0) { + const at = node.items[0]!.start + edits.push({ start: at, end: at, text: `${text}${separator}` }) + } else { + const open = node.start + 1 + edits.push({ + start: open, + end: open, + text: fileMultiline + ? `${layout.style.newline}${childIndent}${newMiddle + .map((item) => formatValue(item, childIndent, true, layout)) + .join(separator)}${layout.style.newline}${indent}` + : text + }) + } + } +} + +const patchObject = ( + value: Record, + node: ObjectNode, + edits: Edit[], + layout: Layout, + indent: string +): void => { + const multiline = isMultiline(layout.text, node) + const childIndent = childIndentForObject(layout, node) || `${indent}${layout.style.unit}` + const separator = multiline + ? `,${layout.style.newline}${childIndent}` + : layout.style.itemSeparator + const byKey = new Map(node.entries.map((entry) => [entry.key, entry])) + + const removedSet = new Set( + node.entries.filter( + (entry) => !Object.prototype.hasOwnProperty.call(value, entry.key) + ) + ) + for (let index = 0; index < node.entries.length; ) { + const entry = node.entries[index]! + if (!removedSet.has(entry)) { + index += 1 + continue + } + let lastIndex = index + while ( + lastIndex + 1 < node.entries.length && + removedSet.has(node.entries[lastIndex + 1]!) + ) { + lastIndex += 1 + } + if (index === 0 && lastIndex === node.entries.length - 1) { + if (Object.keys(value).length === 0) { + edits.push({ start: node.start, end: node.end, text: "{}" }) + return + } + edits.push({ + start: node.start, + end: node.end, + text: formatValue(value, indent, multiline || layout.text.includes("\n"), layout) + }) + return + } + const next = node.entries[lastIndex + 1] + if (next !== undefined) { + edits.push({ + start: node.entries[index]!.keyStart, + end: next.keyStart, + text: "" + }) + } else { + const previous = node.entries[index - 1] + edits.push({ + start: previous !== undefined ? previous.value.end : node.start + 1, + end: node.entries[lastIndex]!.value.end, + text: "" + }) + } + index = lastIndex + 1 + } + + const added = Object.keys(value).filter((key) => !byKey.has(key)) + if (added.length > 0) { + const fileMultiline = multiline || layout.text.includes("\n") + const render = (key: string): string => + `${encodeString(key, layout.style.ensureAscii)}${ + layout.style.keySeparator + }${formatValue(value[key], childIndent, multiline, layout)}` + if (node.entries.length === 0) { + edits.push({ + start: node.start, + end: node.end, + text: formatValue(value, indent, fileMultiline, layout) + }) + return + } + const surviving = node.entries.filter((entry) => !removedSet.has(entry)) + const groups = new Map() + const appended: string[] = [] + let anchorPosition = 0 + for (const key of [...added].sort()) { + while ( + anchorPosition < surviving.length && + surviving[anchorPosition]!.key <= key + ) { + anchorPosition += 1 + } + const anchor = + anchorPosition < surviving.length ? surviving[anchorPosition] : undefined + if (anchor === undefined) { + appended.push(key) + } else { + const bucket = groups.get(anchor.key) + if (bucket === undefined) { + groups.set(anchor.key, { anchor, keys: [key] }) + } else { + bucket.keys.push(key) + } + } + } + for (const { anchor, keys } of groups.values()) { + const text = keys.map(render).join(separator) + edits.push({ + start: anchor.keyStart, + end: anchor.keyStart, + text: fileMultiline ? `${text}${separator}` : `${text}${layout.style.itemSeparator}` + }) + } + if (appended.length > 0) { + const text = appended.map(render).join(separator) + const last = node.entries[node.entries.length - 1] + edits.push({ + start: last!.value.end, + end: last!.value.end, + text: fileMultiline + ? `${separator}${text}` + : `${layout.style.itemSeparator}${text}` + }) + } + } + + for (const [key, next] of Object.entries(value)) { + const entry = byKey.get(key) + if (entry === undefined) continue + patchNode(next, entry.value.value, entry.value, edits, layout, childIndent) + } +} + +const patchNode = ( + value: unknown, + previous: unknown, + node: JsonNode, + edits: Edit[], + layout: Layout, + indent: string +): void => { + if (jsonEqual(value, previous)) return + if (node.kind === "array" && Array.isArray(value)) { + patchArray(value, node, edits, layout, indent) + return + } + if ( + node.kind === "object" && + value !== null && + typeof value === "object" && + !Array.isArray(value) + ) { + patchObject(value as Record, node, edits, layout, indent) + return + } + edits.push({ + start: node.start, + end: node.end, + text: formatValue(value, indent, isMultiline(layout.text, node), layout) + }) +} + +export const applyEdits = (text: string, edits: ReadonlyArray): string | undefined => { + if (edits.length === 0) return text + const ordered = [...edits].sort((a, b) => a.start - b.start || a.end - b.end) + const segments: string[] = [] + let cursor = 0 + for (const edit of ordered) { + if (edit.start < cursor) return undefined + segments.push(text.slice(cursor, edit.start), edit.text) + cursor = edit.end + } + segments.push(text.slice(cursor)) + return segments.join("") +} + +export interface PatchOptions { + readonly style: JsonTextStyle +} + +export type PatchFailureReason = + | "parse-failed" + | "patch-threw" + | "overlapping-edits" + | "not-representable" + | "verification-failed" + | "too-deep" + +export interface PatchResult { + readonly text?: string + readonly reason?: PatchFailureReason +} + +export const patchJsonTextDetailed = ( + text: string, + next: unknown, + options: PatchOptions +): PatchResult => { + let root: JsonNode + let previous: unknown + try { + previous = JSON.parse(text) + root = parseNode(text, 0, 0, previous) + } catch (error) { + if (error instanceof DepthExceededError) return { reason: "too-deep" } + return { reason: "parse-failed" } + } + const layout: Layout = { text, style: options.style } + const edits: Edit[] = [] + try { + patchNode(next, previous, root, edits, layout, "") + } catch (error) { + if (error instanceof RangeError) return { reason: "too-deep" } + return { reason: "patch-threw" } + } + if (edits.length === 0) { + return jsonEqual(previous, next) + ? { text } + : { reason: "not-representable" } + } + const patched = applyEdits(text, edits) + if (patched === undefined) return { reason: "overlapping-edits" } + try { + if (!jsonEqual(JSON.parse(patched), next)) { + return { reason: "verification-failed" } + } + } catch { + return { reason: "verification-failed" } + } + return { text: patched } +} + +export const patchJsonText = ( + text: string, + next: unknown, + options: PatchOptions +): string | undefined => patchJsonTextDetailed(text, next, options).text + +export const jsonDepth = (value: unknown, depth = 0): number => { + if (depth > MAX_JSON_DEPTH) return depth + if (value === null || typeof value !== "object") return depth + let deepest = depth + const children = Array.isArray(value) ? value : Object.values(value as Record) + for (const child of children) { + const childDepth = jsonDepth(child, depth + 1) + if (childDepth > deepest) deepest = childDepth + if (deepest > MAX_JSON_DEPTH) return deepest + } + return deepest +} + +export const formatJsonValue = ( + value: unknown, + style: JsonTextStyle, + multiline = true +): string => { + if (jsonDepth(value) > MAX_JSON_DEPTH) { + throw new DepthExceededError( + `value nesting exceeds the supported depth of ${MAX_JSON_DEPTH}` + ) + } + return formatValue(value, "", multiline, { text: "", style }) +} diff --git a/src/utils/json.ts b/src/utils/json.ts index 06899b5..bed837c 100644 --- a/src/utils/json.ts +++ b/src/utils/json.ts @@ -1,5 +1,15 @@ import { Effect } from "effect" import { NotebookParseError } from "../domain/errors.js" +import { + formatJsonValue, + jsonEqual, + patchJsonTextDetailed, + type JsonTextStyle, + type PatchFailureReason +} from "./json-patch.js" + +export { MAX_JSON_DEPTH } from "./json-patch.js" +export type { PatchFailureReason } export const safeParseJson = ( text: string, @@ -14,5 +24,125 @@ export const safeParseJson = ( }) }) -export const stringifyNotebook = (notebook: unknown): string => - `${JSON.stringify(notebook, null, 1)}\n` +export interface NotebookFormat extends JsonTextStyle { + readonly trailingNewline: boolean +} + +export const DEFAULT_NOTEBOOK_FORMAT: NotebookFormat = { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false, + trailingNewline: true +} + +const indentUnitOf = (prefix: string): string => { + const space = /^( +)/.exec(prefix) + if (space !== null) return " ".repeat(Math.max(1, space[1]!.length)) + if (prefix.startsWith("\t")) return "\t" + return " " +} + +const NON_ASCII_ESCAPE = /\\u(?:00[89a-fA-F][0-9a-fA-F]|0[1-9a-fA-F][0-9a-fA-F]{2}|[1-9a-fA-F][0-9a-fA-F]{3})/g + +const hasAsciiEscapes = (text: string): boolean => { + NON_ASCII_ESCAPE.lastIndex = 0 + for (let match = NON_ASCII_ESCAPE.exec(text); match !== null; match = NON_ASCII_ESCAPE.exec(text)) { + let backslashes = 0 + for (let index = match.index - 1; index >= 0 && text[index] === "\\"; index -= 1) backslashes += 1 + if (backslashes % 2 === 0) return true + } + return false +} + +const separatorOf = (text: string): string => { + const multiline = text.indexOf("\n") !== -1 + if (multiline) return "," + const inline = /,\s*/.exec(text) + return inline !== null && /,\s/.test(inline[0]) ? ", " : "," +} + +const keySeparatorOf = (text: string): string => { + const match = /"(?:[^"\\]|\\.)*"([ \t]*):(\s*)/.exec(text) + if (match === null) return ": " + return `:${match[2]}` +} + +export const detectNotebookFormat = (text: string): NotebookFormat => { + const newline: "\n" | "\r\n" = text.indexOf("\r\n") === -1 ? "\n" : "\r\n" + const trailingNewline = text.endsWith("\n") + const itemSeparator = separatorOf(text) + const keySeparator = keySeparatorOf(text) + const firstBreak = text.indexOf("\n") + const body = trailingNewline ? text.slice(0, -1) : text + if (firstBreak === -1) { + return { + unit: " ", + newline, + itemSeparator, + keySeparator, + ensureAscii: hasAsciiEscapes(text), + trailingNewline + } + } + const secondBreak = text.indexOf("\n", firstBreak + 1) + const secondLine = text.slice( + firstBreak + 1, + secondBreak === -1 ? text.length : secondBreak + ) + return { + unit: indentUnitOf(/^([ \t]+)\S/.exec(secondLine)?.[1] ?? " "), + newline, + itemSeparator, + keySeparator, + ensureAscii: hasAsciiEscapes(body), + trailingNewline + } +} + +export const stringifyNotebook = ( + notebook: unknown, + format: NotebookFormat = DEFAULT_NOTEBOOK_FORMAT +): string => { + const body = formatJsonValue(notebook, format, true) + return format.trailingNewline ? `${body}${format.newline}` : body +} + +export type WriteMode = "patched" | "fallback" + +export interface RewriteResult { + readonly text: string + readonly mode: WriteMode + readonly reason?: PatchFailureReason +} + +export const rewriteNotebookTextDetailed = ( + previousText: string, + notebook: unknown, + format: NotebookFormat +): RewriteResult => { + const patched = patchJsonTextDetailed(previousText, notebook, { style: format }) + if (patched.text !== undefined) { + return { text: patched.text, mode: "patched" } + } + const text = stringifyNotebook(notebook, format) + // The patched path re-parses and compares before it is trusted; the fallback + // used to be returned unverified, so a value JSON cannot represent (an + // `undefined` field, a BigInt) was silently dropped and the write reported + // success. Re-parse here and fall back to an unrepresentable result so the + // caller can refuse instead of losing data. + const reason = patched.reason ?? "not-representable" + try { + if (!jsonEqual(JSON.parse(text), notebook)) { + return { text, mode: "fallback", reason } + } + } catch { + return { text, mode: "fallback", reason } + } + return { + text, + mode: "fallback", + ...(patched.reason === undefined ? {} : { reason: patched.reason }) + } +} diff --git a/src/utils/limits.ts b/src/utils/limits.ts index 732443f..a22ddc2 100644 --- a/src/utils/limits.ts +++ b/src/utils/limits.ts @@ -9,7 +9,6 @@ export const DEFAULT_INSPECT_PREVIEW_CHARS = 240 export const MAX_NOTEBOOK_BYTES = 50 * 1024 * 1024 export const MAX_READ_CELLS = 500 -/** Hard caps that protect the host context from pathological notebooks. */ export const MAX_INSPECT_CELLS = 1_000 export const MAX_METADATA_CHARS = 20_000 export const MAX_RUN_RESPONSE_CHARS = 120_000 diff --git a/src/utils/markdown-safe.ts b/src/utils/markdown-safe.ts index 64b1ca9..3a0e128 100644 --- a/src/utils/markdown-safe.ts +++ b/src/utils/markdown-safe.ts @@ -1,6 +1,5 @@ import { stripAnsi } from "./ansi.js" -/** Single-line label safe inside markdown table/labels. */ export const sanitizeInline = (text: string): string => stripAnsi(text) .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "") @@ -23,7 +22,6 @@ const scanOpenFence = (text: string): OpenFence | undefined => { const opener = OPENER.exec(line) if (opener === null) continue const run = opener[1]! - // A backtick fence's info string may not contain another backtick. if (run[0] === "`" && opener[2]!.includes("`")) continue open = { char: run[0]!, length: Math.min(run.length, MAX_FENCE) } } else { @@ -36,10 +34,19 @@ const scanOpenFence = (text: string): OpenFence | undefined => { return open } -/** - * Truncate rendered markdown without leaving a code fence open. Any fence - * opened before the cut is closed before the truncation hint is appended. - */ +// Slicing a JS string can cut a surrogate pair in half, producing a lone high +// or low surrogate: an invalid UTF-16 sequence that would be written verbatim +// (or mangled by the encoder) if it survived to the notebook. Trim it back to +// the last well-formed boundary. +const wellFormedPrefix = (value: string): string => { + let result = value + if (result.length > 0) { + const last = result.charCodeAt(result.length - 1) + if (last >= 0xd800 && last <= 0xdbff) result = result.slice(0, -1) + } + return result +} + export const truncateMarkdown = ( text: string, maxChars: number, @@ -49,12 +56,12 @@ export const truncateMarkdown = ( if (normalized.length <= maxChars) return normalized const budget = Math.max(0, maxChars - hint.length - MAX_FENCE * 2) let cut = normalized.slice(0, budget) - // Keep pathological marker runs from swallowing the response; 3 markers - // are enough to represent the block once it is closed. cut = cut.replace(/`{33,}/g, "```").replace(/~{33,}/g, "~~~") const open = scanOpenFence(cut) const closing = open === undefined ? "" : `\n${open.char.repeat(open.length)}\n` const result = `${cut.replace(/\n$/, "")}${closing}${hint}` - return result.length <= maxChars ? result : result.slice(0, maxChars) + return wellFormedPrefix( + result.length <= maxChars ? result : result.slice(0, maxChars) + ) } diff --git a/src/utils/metadata.ts b/src/utils/metadata.ts index da47af4..18ed692 100644 --- a/src/utils/metadata.ts +++ b/src/utils/metadata.ts @@ -4,7 +4,6 @@ import { MAX_DIAGNOSTICS_METADATA_BYTES } from "./limits.js" -/** Cap diagnostics metadata by both entry count and serialized bytes. */ export const capDiagnosticMetadata = ( diagnostics: ReadonlyArray ): ReadonlyArray => { diff --git a/src/utils/paths.ts b/src/utils/paths.ts index c61e42b..074f14b 100644 --- a/src/utils/paths.ts +++ b/src/utils/paths.ts @@ -16,6 +16,12 @@ export const normalizeSlashes = (p: string, platform: NodeJS.Platform = process. return p.replace(/\\/g, "/") } +export const absoluteDriveRoot = ( + value: string, + platform: NodeJS.Platform = process.platform +): string => + platform === "win32" && /^[A-Za-z]:$/.test(value) ? `${value}\\` : value + export const isAbsolutePath = (p: string): boolean => { if (!p) { return false @@ -72,3 +78,20 @@ export const makeRelative = ( } export const toForwardSlashes = (p: string): string => p.replace(/\\/g, "/") + +export const pathInside = ( + root: string, + target: string, + platform: NodeJS.Platform = process.platform +): boolean => { + const relative = path.relative( + absoluteDriveRoot(root, platform), + absoluteDriveRoot(target, platform) + ) + return ( + relative === "" || + (relative !== ".." && + !relative.startsWith(`..${path.sep}`) && + !path.isAbsolute(relative)) + ) +} diff --git a/src/utils/realpath.ts b/src/utils/realpath.ts new file mode 100644 index 0000000..3c1be9f --- /dev/null +++ b/src/utils/realpath.ts @@ -0,0 +1,30 @@ +import * as fsp from "node:fs/promises" +import * as path from "node:path" + +const ATTEMPTS = 3 + +const parentIsStable = async (target: string): Promise => { + const parent = path.dirname(target) + if (parent === target) return false + try { + await fsp.stat(parent) + return true + } catch { + return false + } +} + +export const realpathWithRetry = async (target: string): Promise => { + let failure: unknown + for (let attempt = 0; attempt < ATTEMPTS; attempt += 1) { + try { + return await fsp.realpath(target) + } catch (error) { + failure = error + if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error + if (!(await parentIsStable(target))) throw error + if (attempt + 1 < ATTEMPTS) await new Promise((resolve) => setImmediate(resolve)) + } + } + throw failure +} diff --git a/src/utils/rename-hook.ts b/src/utils/rename-hook.ts new file mode 100644 index 0000000..b903aec --- /dev/null +++ b/src/utils/rename-hook.ts @@ -0,0 +1,20 @@ +type RenameHook = (target: string) => Promise | void + +let beforeHook: RenameHook | undefined +let afterHook: RenameHook | undefined + +export const setBeforeRenameHook = (next: RenameHook | undefined): void => { + beforeHook = next +} + +export const setAfterRenameHook = (next: RenameHook | undefined): void => { + afterHook = next +} + +export const beforeRenameHook = async (target: string): Promise => { + if (beforeHook !== undefined) await beforeHook(target) +} + +export const afterRenameHook = async (target: string): Promise => { + if (afterHook !== undefined) await afterHook(target) +} diff --git a/src/utils/truncate.ts b/src/utils/truncate.ts index 30c261a..ba6cb96 100644 --- a/src/utils/truncate.ts +++ b/src/utils/truncate.ts @@ -44,9 +44,6 @@ export const truncate = (text: string, maxChars: number, hint: TruncateHint = "t const suffix = buildSuffix(hint, maxChars) const budget = Math.max(0, maxChars - suffix.length) if (budget === 0) { - // The hint alone is at least as long as the budget. Drop the original - // text so the user still sees a "truncated" indicator instead of - // silently returning a result that exceeds `maxChars`. return { text: suffix, truncated: true, @@ -69,8 +66,6 @@ export const truncatePreview = (text: string, maxChars: number): string => { if (text.length <= maxChars) { return text } - // 16 chars is the length of the literal suffix "\n... (truncated)" so that the - // returned preview never exceeds `maxChars` even for very small budgets. return text.slice(0, Math.max(0, maxChars - 16)) + "\n... (truncated)" } diff --git a/src/utils/warnings.ts b/src/utils/warnings.ts new file mode 100644 index 0000000..110c2f2 --- /dev/null +++ b/src/utils/warnings.ts @@ -0,0 +1,78 @@ +import { Effect } from "effect" + +export type WarningSource = + | "atomic-replace" + | "cleanup" + | "json-patch" + | "lock" + | "permission-alias" + | "path-resolution" + | "python-probe" + | "revision-check" + | "shell-command" + | "sidecar-cleanup" + | "temp-unlink" + +export interface Warning { + readonly source: WarningSource + readonly message: string + readonly detail?: string +} + +export interface WarningSink { + readonly add: (warning: Warning) => void + readonly drain: () => ReadonlyArray +} + +export const makeWarningSink = (): WarningSink => { + let warnings: Warning[] = [] + return { + add: (warning) => { + warnings.push(warning) + }, + drain: () => { + const drained = warnings + warnings = [] + return drained + } + } +} + +export const warningFrom = ( + source: WarningSource, + error: unknown, + context?: string +): Warning => { + const message = error instanceof Error ? error.message : String(error) + const code = (error as NodeJS.ErrnoException | undefined)?.code + const detail = context === undefined ? code : `${context}: ${code ?? message}` + return { + source, + message, + ...(detail === undefined ? {} : { detail }) + } +} + +export const ignoreExpectedFailure = ( + sink: WarningSink | undefined, + source: WarningSource, + context: string, + effect: Effect.Effect +): Effect.Effect => + Effect.orElseSucceed(effect, (error) => { + sink?.add(warningFrom(source, error, context)) + return undefined + }) + +export const bestEffort = async ( + sink: WarningSink | undefined, + source: WarningSource, + context: string, + action: () => Promise +): Promise => { + try { + await action() + } catch (error) { + sink?.add(warningFrom(source, error, context)) + } +} diff --git a/src/utils/windows.ts b/src/utils/windows.ts index 23daf0a..8668377 100644 --- a/src/utils/windows.ts +++ b/src/utils/windows.ts @@ -1,22 +1,24 @@ import { spawn } from "node:child_process" import * as path from "node:path" +import { type WarningSink, warningFrom } from "./warnings.js" -/** Absolute taskkill path so CreateProcess never searches the project cwd. */ export const taskkillPath = (): string => { const root = process.env.SystemRoot ?? process.env.WINDIR ?? "C:\\Windows" return path.join(root, "System32", "taskkill.exe") } -/** Best-effort taskkill with an error listener (never crashes the host). */ -export const killWindowsTree = (pid: number): void => { +export const killWindowsTree = (pid: number, sink?: WarningSink): void => { + const context = `taskkill ${pid}` try { const child = spawn(taskkillPath(), ["/pid", String(pid), "/T", "/F"], { windowsHide: true, stdio: "ignore" }) - child.on("error", () => {}) - } catch { - // ignore + child.on("error", (error) => { + sink?.add(warningFrom("cleanup", error, context)) + }) + } catch (error) { + sink?.add(warningFrom("cleanup", error, context)) } } diff --git a/src/virtual-materialize.ts b/src/virtual-materialize.ts index 709a664..4d2e5d6 100644 --- a/src/virtual-materialize.ts +++ b/src/virtual-materialize.ts @@ -5,13 +5,19 @@ import { replaceFile } from "./utils/atomic-replace.js" import * as path from "node:path" import type { NotebookVirtualDocument } from "./lsp.js" import { sanitizeNotebookText } from "./notebook-diagnostics.js" +import { pathInside } from "./utils/paths.js" +import { beforeRenameHook } from "./utils/rename-hook.js" +import { + type Warning, + type WarningSink, + makeWarningSink, + warningFrom +} from "./utils/warnings.js" export interface MaterializedCell { readonly cellIndex: number readonly cellType: string - /** First line in the materialized file, 1-based and inclusive. */ readonly startLine: number - /** Last line in the materialized file, 1-based and inclusive. */ readonly endLine: number } @@ -19,32 +25,40 @@ export interface MaterializedDocument { readonly path: string readonly text: string readonly cells: ReadonlyArray + readonly warnings?: ReadonlyArray +} + +export interface MaterializeOptions { + readonly warningSink?: WarningSink | undefined +} + +export interface CleanupOptions { + readonly warningSink?: WarningSink +} + +const isMissing = (error: unknown): boolean => { + const code = (error as NodeJS.ErrnoException | undefined)?.code + return code === "ENOENT" || code === "ENOTDIR" } -// The sidecar lives next to the notebook, not in a session-level cache: -// pyright resolves sibling imports relative to the analyzed file's directory. -// A visible (non-dot) filename is required because pyright excludes dotfiles -// by default. const SIDECAR_PREFIX = "opencode-ipynb-lsp-" const LEGACY_DIRECTORY = ".opencode/ipynb-lsp" const LEGACY_FILE = /\.[0-9a-f]{16}\.py$/ const MAX_AGE_MS = 60 * 60 * 1000 -const inside = (root: string, target: string): boolean => { - const relative = path.relative(root, target) - return ( - relative === "" || - (relative !== ".." && - !relative.startsWith(`..${path.sep}`) && - !path.isAbsolute(relative)) - ) -} - +// realpath only resolves what already exists. A virtual document can name a +// notebook that does not exist on disk yet, and on macOS the temp dir itself is +// a symlink (/tmp -> /private/tmp): returning the lexical spelling for a +// missing file made the root-containment check compare two spellings of one +// directory, so the sidecar fell back outside the session root. Resolve the +// deepest existing ancestor and keep the missing tail lexical. const realPath = (filePath: string): string => { try { return fs.realpathSync(filePath) } catch { - return filePath + const parent = path.dirname(filePath) + if (parent === filePath) return filePath + return path.join(realPath(parent), path.basename(filePath)) } } @@ -54,12 +68,11 @@ const hashFor = (filePath: string): string => const fileNameFor = (filePath: string): string => `${SIDECAR_PREFIX}${hashFor(filePath)}.py` -/** Path of the materialized sidecar for a notebook. */ export const materializedPath = (filePath: string, root?: string): string => { const realFile = realPath(filePath) if (root !== undefined) { const rootReal = realPath(root) - if (inside(rootReal, realFile)) { + if (pathInside(rootReal, realFile)) { const lexicalRoot = path.resolve(root) const relative = path.relative(rootReal, realFile) return path.join(lexicalRoot, path.dirname(relative), fileNameFor(filePath)) @@ -67,75 +80,119 @@ export const materializedPath = (filePath: string, root?: string): string => { } const lexicalDir = path.dirname(path.resolve(filePath)) const realDir = path.dirname(realFile) - // If the lexical directory is a symlinked session root, keep the lexical - // path: the external lsp tool checks `within(root, file)` lexically before - // resolving. Otherwise (a symlinked notebook file) use the real directory - // so pyright can resolve sibling imports. try { if (fs.realpathSync(lexicalDir) === realDir) { return path.join(lexicalDir, fileNameFor(filePath)) } } catch { - // fall through to the real directory } return path.join(realDir, fileNameFor(filePath)) } -// Files created by this process, scoped by the worktree used to materialize -// them. Unloading one project must not untrack another project's sidecar; old -// files from a crashed process are overwritten by the next materialize. const activeSidecars = new Map>() +const trackSidecar = ( + rootReal: string, + safeTarget: string, + target: string +): string => { + const tracked = activeSidecars.get(rootReal) ?? new Set() + tracked.add(safeTarget) + activeSidecars.set(rootReal, tracked) + return target +} + const writeSidecar = async ( worktree: string, filePath: string, - text: string + text: string, + sink: WarningSink | undefined ): Promise => { const rootReal = await fsp.realpath(worktree) const target = materializedPath(filePath, worktree) const directoryReal = await fsp.realpath(path.dirname(target)) - if (!inside(rootReal, directoryReal)) { + if (!pathInside(rootReal, directoryReal)) { throw new Error(`Refusing to write outside the session directory: ${target}`) } const safeTarget = path.join(directoryReal, path.basename(target)) + const existing = await fsp.lstat(safeTarget).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `inspecting ${safeTarget}`)) + } + return undefined + }) + if (existing?.isDirectory()) { + throw new Error(`Refusing to replace a directory: ${safeTarget}`) + } + if (existing?.isFile()) { + const current = await fsp.readFile(safeTarget, "utf8").catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `reading ${safeTarget}`)) + } + return undefined + }) + if (current === text) { + return trackSidecar(rootReal, safeTarget, target) + } + } const temp = path.join( directoryReal, `${SIDECAR_PREFIX}${randomBytes(6).toString("hex")}.tmp` ) try { await fsp.writeFile(temp, text, { encoding: "utf8", flag: "wx", mode: 0o600 }) - const existing = await fsp.lstat(safeTarget).catch(() => undefined) - if (existing?.isDirectory()) { - throw new Error(`Refusing to replace a directory: ${safeTarget}`) + await beforeRenameHook(safeTarget) + const freshDir = await fsp.realpath(path.dirname(safeTarget)) + if (!pathInside(rootReal, freshDir)) { + throw new Error(`Refusing to write outside the session directory: ${freshDir}`) + } + const freshTarget = path.join(freshDir, path.basename(safeTarget)) + if (freshTarget !== safeTarget) { + const moved = path.join(freshDir, path.basename(temp)) + await fsp.rename(temp, moved) + await replaceFile(moved, freshTarget, sink) + return trackSidecar(rootReal, freshTarget, target) } - // Rename is atomic on POSIX and replaces the target. A pre-existing - // symlink is replaced, never followed. The Windows fallback keeps a - // backup instead of deleting the original first. - await replaceFile(temp, safeTarget) + await replaceFile(temp, safeTarget, sink) } catch (error) { - await fsp.rm(temp, { force: true }).catch(() => {}) + await fsp.rm(temp, { force: true }).catch((cleanupError: unknown) => { + sink?.add(warningFrom("temp-unlink", cleanupError, `left ${temp}`)) + }) throw error } - const tracked = activeSidecars.get(rootReal) ?? new Set() - tracked.add(safeTarget) - activeSidecars.set(rootReal, tracked) - return target + return trackSidecar(rootReal, safeTarget, target) } -const cleanupLegacyDirectory = async (rootReal: string): Promise => { +const cleanupLegacyDirectory = async ( + rootReal: string, + sink: WarningSink | undefined +): Promise => { const directory = path.join(rootReal, LEGACY_DIRECTORY) - const stat = await fsp.lstat(directory).catch(() => undefined) + const stat = await fsp.lstat(directory).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `inspecting ${directory}`)) + } + return undefined + }) if (stat === undefined) return if (stat.isSymbolicLink()) { await fsp.rm(directory, { force: true }) return } - const real = await fsp.realpath(directory).catch(() => undefined) - if (real === undefined || !inside(rootReal, real)) { + const real = await fsp.realpath(directory).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `resolving ${directory}`)) + } + return undefined + }) + if (real === undefined || !pathInside(rootReal, real)) { throw new Error(`Refusing to clean a materialized directory outside the worktree`) } const now = Date.now() - const entries = await fsp.readdir(real, { withFileTypes: true }).catch(() => []) + const entries = await fsp.readdir(real, { withFileTypes: true }).catch((error: unknown) => { + sink?.add(warningFrom("sidecar-cleanup", error, `listing ${real}`)) + return [] + }) await Promise.all( entries .filter( @@ -145,98 +202,184 @@ const cleanupLegacyDirectory = async (rootReal: string): Promise => { ) .map(async (entry) => { const file = path.join(real, entry.name) - const info = await fsp.stat(file).catch(() => undefined) + const info = await fsp.stat(file).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `inspecting ${file}`)) + } + return undefined + }) if (info !== undefined && now - info.mtimeMs > MAX_AGE_MS) { - await fsp.rm(file, { force: true }).catch(() => {}) + await fsp.rm(file, { force: true }).catch((error: unknown) => { + sink?.add(warningFrom("sidecar-cleanup", error, `removing ${file}`)) + }) } }) ) - await fsp.rmdir(real).catch(() => {}) - await fsp.rmdir(path.dirname(real)).catch(() => {}) + await fsp.rmdir(real).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code !== "ENOTEMPTY") { + sink?.add(warningFrom("sidecar-cleanup", error, `removing ${real}`)) + } + }) + await fsp.rmdir(path.dirname(real)).catch((error: unknown) => { + if ((error as NodeJS.ErrnoException).code !== "ENOTEMPTY") { + sink?.add( + warningFrom("sidecar-cleanup", error, `removing ${path.dirname(real)}`) + ) + } + }) } -/** - * Write the notebook's virtual Python document beside the notebook so an - * external LSP plugin can open it with its own `lsp` tool. The path must stay - * inside the session/worktree (opencode-v2-lsp-support rejects paths outside - * its root), and living next to the notebook lets pyright resolve sibling - * imports exactly like the notebook itself. - * - * IPython magics are blanked exactly like the diagnostics path, preserving - * line/column positions so hover and definitions still map to cells. - */ export const materializeVirtualDocument = async ( document: NotebookVirtualDocument, - worktree: string + worktree: string, + options?: MaterializeOptions ): Promise => { - const text = sanitizeNotebookText(document) - const file = await writeSidecar(worktree, document.filePath, text) - return { - path: file, - text, - cells: document.cells.map((cell) => ({ - cellIndex: cell.cellIndex, - cellType: cell.cellType, - startLine: cell.startLine + 1, - endLine: Math.max(cell.startLine + 1, cell.endLine) - })) + const sink = makeWarningSink() + const forward = (): ReadonlyArray => { + const warnings = sink.drain() + for (const warning of warnings) options?.warningSink?.add(warning) + return warnings + } + try { + const text = sanitizeNotebookText(document) + const file = await writeSidecar(worktree, document.filePath, text, sink) + const warnings = forward() + return { + path: file, + text, + cells: document.cells.map((cell) => ({ + cellIndex: cell.cellIndex, + cellType: cell.cellType, + startLine: cell.startLine + 1, + endLine: Math.max(cell.startLine + 1, cell.endLine) + })), + ...(warnings.length === 0 ? {} : { warnings }) + } + } catch (error) { + forward() + throw error } } -/** - * Refresh an already materialized document after an edit. Does nothing until - * the notebook has been materialized at least once. - */ export const refreshMaterializedDocument = async ( document: NotebookVirtualDocument, - worktree: string + worktree: string, + options?: MaterializeOptions ): Promise => { const existing = await fsp .lstat(materializedPath(document.filePath, worktree)) - .catch(() => undefined) + .catch((error: unknown) => { + if (!isMissing(error)) { + options?.warningSink?.add( + warningFrom( + "sidecar-cleanup", + error, + `inspecting ${materializedPath(document.filePath, worktree)}` + ) + ) + } + return undefined + }) if (existing === undefined) return false - await writeSidecar(worktree, document.filePath, sanitizeNotebookText(document)) + await writeSidecar( + worktree, + document.filePath, + sanitizeNotebookText(document), + options?.warningSink + ) return true } -/** True when this notebook already has a materialized sidecar. */ export const hasMaterializedDocument = async ( worktree: string, - filePath: string + filePath: string, + options?: MaterializeOptions ): Promise => { - const rootReal = await fsp.realpath(worktree).catch(() => undefined) + const sink = options?.warningSink + const rootReal = await fsp.realpath(worktree).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `resolving ${worktree}`)) + } + return undefined + }) if (rootReal === undefined) return false const target = materializedPath(filePath, worktree) const targetDirReal = await fsp .realpath(path.dirname(target)) - .catch(() => undefined) - if (targetDirReal === undefined || !inside(rootReal, targetDirReal)) return false - const stat = await fsp.lstat(target).catch(() => undefined) + .catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add( + warningFrom( + "sidecar-cleanup", + error, + `resolving ${path.dirname(target)}` + ) + ) + } + return undefined + }) + if (targetDirReal === undefined || !pathInside(rootReal, targetDirReal)) return false + const stat = await fsp.lstat(target).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `inspecting ${target}`)) + } + return undefined + }) return stat !== undefined } -/** Remove only this plugin's materialized documents. */ -export const cleanupVirtualDocuments = async (worktree: string): Promise => { - const rootReal = await fsp.realpath(worktree).catch(() => undefined) +export const cleanupVirtualDocuments = async ( + worktree: string, + options?: CleanupOptions +): Promise => { + const sink = options?.warningSink + const rootReal = await fsp.realpath(worktree).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `resolving ${worktree}`)) + } + return undefined + }) if (rootReal === undefined) return const tracked = activeSidecars.get(rootReal) if (tracked !== undefined) { + const snapshot = [...tracked] + const failed = new Set() await Promise.all( - [...tracked].map(async (file) => { - // Resolve the parent immediately before removing: a directory can be - // replaced by a symlink after materialization, and rm would follow it. + snapshot.map(async (file) => { const parentReal = await fsp .realpath(path.dirname(file)) - .catch(() => undefined) - if (parentReal === undefined || !inside(rootReal, parentReal)) return + .catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add( + warningFrom("sidecar-cleanup", error, `resolving ${path.dirname(file)}`) + ) + } + return undefined + }) + if (parentReal === undefined || !pathInside(rootReal, parentReal)) return const target = path.join(parentReal, path.basename(file)) - const stat = await fsp.lstat(target).catch(() => undefined) - if (stat !== undefined && !stat.isDirectory()) { - await fsp.rm(target, { force: true }).catch(() => {}) - } + const stat = await fsp.lstat(target).catch((error: unknown) => { + if (!isMissing(error)) { + sink?.add(warningFrom("sidecar-cleanup", error, `inspecting ${target}`)) + } + return undefined + }) + if (stat === undefined || stat.isDirectory()) return + const removed = await fsp.rm(target, { force: true }).then( + () => true, + (error: unknown) => { + sink?.add(warningFrom("sidecar-cleanup", error, `removing ${target}`)) + return false + } + ) + if (!removed) failed.add(file) }) ) - activeSidecars.delete(rootReal) + const latest = activeSidecars.get(rootReal) ?? tracked + for (const file of snapshot) { + if (!failed.has(file)) latest.delete(file) + } + if (latest.size === 0) activeSidecars.delete(rootReal) } - await cleanupLegacyDirectory(rootReal) + await cleanupLegacyDirectory(rootReal, sink) } diff --git a/test/helpers.ts b/test/helpers.ts index 5051124..461f727 100644 --- a/test/helpers.ts +++ b/test/helpers.ts @@ -1,5 +1,24 @@ import { describe } from "bun:test" import { spawnSync } from "node:child_process" +import * as fs from "node:fs" + +/** + * True when both paths denote the same physical file or directory. + * + * macOS spells the temp dir through a symlink (/tmp -> /private/tmp) and + * Windows through 8.3 short names (RUNNER~1), so the implementation's resolved + * paths and a test's lexical paths are two spellings of one inode. Spy hooks + * and assertions must compare what a path denotes, not how it is spelled. + */ +export const samePhysicalPath = (a: string, b: string): boolean => { + try { + const left = fs.statSync(a) + const right = fs.statSync(b) + return left.ino === right.ino && left.dev === right.dev + } catch { + return false + } +} export const pythonHas = (module: string): boolean => { const code = `import sys, importlib.util; sys.exit(0 if importlib.util.find_spec("${module}") else 1)` diff --git a/test/integration/warm-kernel.test.ts b/test/integration/warm-kernel.test.ts index 5689710..f946c0b 100644 --- a/test/integration/warm-kernel.test.ts +++ b/test/integration/warm-kernel.test.ts @@ -269,6 +269,7 @@ describeIf(realHelperEnabled(), "integration > warm kernel > source reload", () maxOutputChars: 4_000 }) ) + await run(20_000) await run(1_000) const pid = kernel.list()[0]?.pid fs.writeFileSync( diff --git a/test/unit/abort-guard.test.ts b/test/unit/abort-guard.test.ts new file mode 100644 index 0000000..ebd2ab6 --- /dev/null +++ b/test/unit/abort-guard.test.ts @@ -0,0 +1,97 @@ +import { describe, expect, it } from "bun:test" +import type { Plugin } from "@opencode/plugin" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { toV2Tool } from "../../src/plugin-v2.js" +import { v2ToolRegistrations } from "../../src/registrations.js" +import { ipynbEditTool } from "../../src/tools/edit.js" +import type { ToolContext } from "../../src/tool.js" + +const notebook = `${JSON.stringify( + { + cells: [ + { cell_type: "markdown", metadata: {}, source: ["# A"] } + ], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 +)}\n` + +const pluginContext = (dir: string): Plugin.Context => + ({ + location: { directory: dir, project: { directory: dir } }, + options: {}, + permission: { assert: async () => {} }, + tool: { transform: async () => ({ dispose: async () => {} }) } + }) as unknown as Plugin.Context + +const registration = v2ToolRegistrations.find( + (entry) => entry.name === "ipynb_edit" +)! + +describe("an already-cancelled tool call", () => { + it("changes nothing and reports the cancellation", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-abort-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const before = fs.readFileSync(file) + const controller = new AbortController() + controller.abort() + try { + const toolInfo = toV2Tool(pluginContext(dir), registration, {}) + const result = (await toolInfo.execute( + { filePath: file, cellIndex: 0, source: "# B", clearOutputs: "never" }, + { + sessionID: "ses_1", + messageID: "msg_1", + agent: "build", + id: "call_1", + signal: controller.signal, + progress: async () => {} + } as never + )) as { content: string; metadata?: { error?: boolean; message?: string } } + expect(result.content).toContain("cancelled") + expect(result.metadata?.error).toBe(true) + expect(fs.readFileSync(file).equals(before)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("also refuses a raw tool definition invoked directly", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-abort-raw-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const before = fs.readFileSync(file) + const controller = new AbortController() + controller.abort() + try { + const result = await ipynbEditTool.execute( + { + filePath: file, + cellIndex: 0, + source: "# RAW", + clearOutputs: "never" + }, + { + sessionID: "t", + messageID: "t", + agent: "t", + directory: dir, + worktree: dir, + abort: controller.signal, + metadata: () => {}, + ask: async () => {} + } as unknown as ToolContext + ) + expect(typeof result !== "string" && result.metadata?.error).toBe(true) + expect(fs.readFileSync(file).equals(before)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/atomic-replace.test.ts b/test/unit/atomic-replace.test.ts new file mode 100644 index 0000000..41c7f5f --- /dev/null +++ b/test/unit/atomic-replace.test.ts @@ -0,0 +1,88 @@ +import { describe, expect, it, spyOn } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { replaceFile } from "../../src/utils/atomic-replace.js" +import { makeWarningSink } from "../../src/utils/warnings.js" + +const withTempDir = async (fn: (dir: string) => Promise): Promise => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "atomic-")) + try { + await fn(dir) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +describe("replaceFile", () => { + it("renames the temp file over the target", async () => { + await withTempDir(async (dir) => { + const temp = path.join(dir, "new.tmp") + const target = path.join(dir, "notebook.ipynb") + fs.writeFileSync(temp, "new") + fs.writeFileSync(target, "old") + await replaceFile(temp, target) + expect(fs.readFileSync(target, "utf8")).toBe("new") + expect(fs.existsSync(temp)).toBe(false) + }) + }) + + it("creates the target when it does not exist yet", async () => { + await withTempDir(async (dir) => { + const temp = path.join(dir, "new.tmp") + const target = path.join(dir, "fresh.ipynb") + fs.writeFileSync(temp, "content") + await replaceFile(temp, target) + expect(fs.readFileSync(target, "utf8")).toBe("content") + }) + }) + + it("rejects instead of deleting both copies when the rename fails", async () => { + await withTempDir(async (dir) => { + const temp = path.join(dir, "new.tmp") + const target = path.join(dir, "notebook.ipynb") + fs.writeFileSync(temp, "new") + fs.mkdirSync(target) + fs.writeFileSync(path.join(target, "inner"), "keep") + const sink = makeWarningSink() + await expect(replaceFile(temp, target, sink)).rejects.toBeDefined() + expect(fs.existsSync(path.join(target, "inner"))).toBe(true) + }) + }) + + it("reports when it cannot move the target aside", async () => { + if (process.platform !== "win32") return + await withTempDir(async (dir) => { + const temp = path.join(dir, "new.tmp") + const target = path.join(dir, "notebook.ipynb") + fs.writeFileSync(temp, "new") + fs.writeFileSync(target, "old") + const original = fs.promises.rename + let firstAttempt = true + const spy = spyOn(fs.promises, "rename").mockImplementation((( + from: fs.PathLike, + to: fs.PathLike + ) => { + if (firstAttempt) { + firstAttempt = false + return Promise.reject( + Object.assign(new Error("locked"), { code: "EPERM" }) + ) + } + if (path.resolve(String(from)) === path.resolve(target)) { + return Promise.reject( + Object.assign(new Error("locked"), { code: "EPERM" }) + ) + } + return original(from, to) + }) as unknown as typeof fs.promises.rename) + try { + const sink = makeWarningSink() + await replaceFile(temp, target, sink) + expect(sink.drain().length).toBeGreaterThan(0) + } finally { + spy.mockRestore() + } + }) + }) +}) diff --git a/test/unit/cancel-during-prompt.test.ts b/test/unit/cancel-during-prompt.test.ts new file mode 100644 index 0000000..0855ae1 --- /dev/null +++ b/test/unit/cancel-during-prompt.test.ts @@ -0,0 +1,112 @@ +import { describe, expect, it } from "bun:test" +import { Cause, Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { + makeCleanImpl, + makeEditImpl, + makeOutputImpl, + makeNotebookFileService, + makePathService, + makePermissionService +} from "../../src/services/index.js" +import type { ToolContext } from "../../src/tool.js" + +const notebook = `${JSON.stringify( + { + cells: [ + { + cell_type: "code", + execution_count: 3, + metadata: {}, + outputs: [{ output_type: "stream", name: "stdout", text: ["hi\n"] }], + source: ["print(1)"] + }, + { cell_type: "markdown", metadata: {}, source: ["# B"] } + ], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 +)}\n` + +const cancellingContext = (dir: string): { context: ToolContext; controller: AbortController } => { + const controller = new AbortController() + return { + controller, + context: { + sessionID: "t", + messageID: "t", + agent: "t", + directory: dir, + worktree: dir, + abort: controller.signal, + metadata: () => {}, + ask: async () => { + controller.abort() + } + } as unknown as ToolContext + } +} + +const build = (dir: string, context: ToolContext) => { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const fileSvc = makeNotebookFileService({ + worktree: dir, + signal: context.abort + }) + const permSvc = makePermissionService(context) + return { + edit: makeEditImpl(pathSvc, fileSvc, permSvc), + clean: makeCleanImpl(pathSvc, fileSvc, permSvc), + output: makeOutputImpl(pathSvc, fileSvc, permSvc) + } +} + +const operations: Record< + string, + (file: string, services: ReturnType) => Effect.Effect +> = { + editCell: (file, services) => + services.edit.editCell(file, { cellIndex: 0, source: "print(2)", clearOutputs: "always" }), + insertCell: (file, services) => services.edit.insertCell(file, "markdown", "# C", 1), + deleteCell: (file, services) => services.edit.deleteCell(file, 0), + moveCell: (file, services) => services.edit.moveCell(file, 0, 1), + clean: (file, services) => services.clean.clean(file, { clearOutputs: true }), + clearCellOutputs: (file, services) => services.output.clearCellOutputs(file, 0), + clearAllOutputs: (file, services) => services.output.clearAllOutputs(file) +} + +describe("a cancellation during the permission prompt never writes", () => { + for (const [name, operation] of Object.entries(operations)) { + it(`leaves the file byte-identical when ${name} is cancelled in ask`, async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-midcancel-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const before = fs.readFileSync(file) + const { context, controller } = cancellingContext(dir) + try { + const exit = await Effect.runPromiseExit( + operation(file, build(dir, context)) + ) + expect(controller.signal.aborted).toBe(true) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.findErrorOption(exit.cause) + expect(error._tag).toBe("Some") + } + expect(fs.readFileSync(file).equals(before)).toBe(true) + expect(fs.readdirSync(dir).filter((entry) => entry.endsWith(".tmp"))).toEqual([]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + } +}) diff --git a/test/unit/clean-normalized-count.test.ts b/test/unit/clean-normalized-count.test.ts new file mode 100644 index 0000000..28d11e3 --- /dev/null +++ b/test/unit/clean-normalized-count.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { makeCleanImpl } from "../../src/services/NotebookCleanService.js" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { makePathService } from "../../src/services/PathService.js" +import { makePermissionService } from "../../src/services/PermissionService.js" +import type { ToolContext } from "../../src/tool.js" + +const ctx = (dir: string) => + ({ + sessionID: "t", + messageID: "t", + agent: "t", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + }) as unknown as ToolContext + +const run = async (effect: Effect.Effect) => + Effect.runPromise(effect as Effect.Effect) + +const notebook = () => ({ + nbformat: 4, + nbformat_minor: 5, + metadata: {}, + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: ["a = 1\n"] + }, + { + cell_type: "markdown", + metadata: {}, + source: ["# title\n"] + }, + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "b = 2\n" + } + ] +}) + +const cleanIn = async (options: Record) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "clean-count-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook())) + try { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const clean = makeCleanImpl( + pathSvc, + makeNotebookFileService(), + makePermissionService(ctx(dir)) + ) + return await run(clean.clean(file, options)) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +describe("ipynb_clean normalized source count", () => { + it("counts the cells whose source arrays it joined", async () => { + const result = await cleanIn({}) + expect(result.normalizedSources).toBe(2) + expect(result.affectedCells).toBe(2) + }) + + it("counts zero when normalization is disabled", async () => { + const result = await cleanIn({ normalizeSource: false }) + expect(result.normalizedSources).toBe(0) + expect(result.affectedCells).toBe(0) + }) +}) diff --git a/test/unit/concurrent-replacement.test.ts b/test/unit/concurrent-replacement.test.ts new file mode 100644 index 0000000..212ad1a --- /dev/null +++ b/test/unit/concurrent-replacement.test.ts @@ -0,0 +1,174 @@ +import { describe, expect, it, spyOn } from "bun:test" +import { Cause, Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { NotebookValidationError } from "../../src/domain/errors.js" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { setAfterRenameHook } from "../../src/utils/rename-hook.js" +import { samePhysicalPath } from "../helpers.js" + +const notebook = (source: string): string => + `${JSON.stringify( + { + cells: [{ cell_type: "markdown", metadata: {}, source: [source] }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 + )}\n` + +describe("concurrent replacement detection", () => { + it("reports the loss when another process deletes the notebook after our rename", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-deleted-")) + const file = path.join(dir, "n.ipynb") + const before = notebook("# A") + fs.writeFileSync(file, before) + const format = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false, + trailingNewline: true + } + setAfterRenameHook(() => { + fs.rmSync(file, { force: true }) + }) + try { + const svc = makeNotebookFileService({ worktree: dir }) + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, JSON.parse(notebook("# OURS")) as never, { + format, + previousText: before + }) + ) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.findErrorOption(exit.cause) + const value = error._tag === "Some" ? error.value : undefined + expect((value as { message?: string }).message ?? "").toContain("disappeared") + } + expect(fs.existsSync(file)).toBe(false) + } finally { + setAfterRenameHook(undefined) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports a lost write when another writer rewrites the file in place", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-inplace-")) + const file = path.join(dir, "n.ipynb") + const before = notebook("# A") + fs.writeFileSync(file, before) + const format = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false, + trailingNewline: true + } + const original = fs.promises.rename + let injected = false + let inodeBefore: number | undefined + let inodeAfter: number | undefined + const spy = spyOn(fs.promises, "rename").mockImplementation((( + from: fs.PathLike, + to: fs.PathLike + ) => { + return original(from, to).then((result) => { + // The implementation renames to the realpath-resolved target: on + // macOS the temp dir is a symlink and on Windows it is an 8.3 short + // name, so the resolved spelling differs from the lexical one. Match + // what the target denotes instead of how it is spelled. The temp's + // own move (to a not-yet-existing name) fails the stat check and is + // skipped, so only the final rename can inject. + if (!injected && samePhysicalPath(String(to), file)) { + injected = true + inodeBefore = fs.statSync(file).ino + fs.writeFileSync(file, notebook("# IN-PLACE")) + inodeAfter = fs.statSync(file).ino + } + return result + }) + }) as unknown as typeof fs.promises.rename) + try { + const svc = makeNotebookFileService({ worktree: dir }) + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, JSON.parse(notebook("# OURS")) as never, { + format, + previousText: before + }) + ) + expect(inodeBefore).toBe(inodeAfter) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.findErrorOption(exit.cause) + expect(error._tag === "Some" ? error.value : undefined).toBeInstanceOf( + NotebookValidationError + ) + } + expect(fs.readFileSync(file, "utf8")).toBe(notebook("# IN-PLACE")) + } finally { + spy.mockRestore() + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports a lost write when another writer replaces the file after our rename", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-lost-")) + const file = path.join(dir, "n.ipynb") + const before = notebook("# A") + fs.writeFileSync(file, before) + const format = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false, + trailingNewline: true + } + const original = fs.promises.rename + let injected = false + const spy = spyOn(fs.promises, "rename").mockImplementation((( + from: fs.PathLike, + to: fs.PathLike + ) => { + return original(from, to).then((result) => { + // Same as above: match the resolved target physically, not lexically. + if (!injected && samePhysicalPath(String(to), file)) { + injected = true + const competitor = path.join(dir, "competitor.tmp") + fs.writeFileSync(competitor, notebook("# COMPETITOR")) + return original(competitor, to).then(() => result) + } + return result + }) + }) as unknown as typeof fs.promises.rename) + try { + const svc = makeNotebookFileService({ worktree: dir }) + const exit = await Effect.runPromiseExit( + svc.writeAtomic( + file, + JSON.parse(notebook("# OURS")) as never, + { format, previousText: before } + ) + ) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.findErrorOption(exit.cause) + expect(error._tag === "Some" ? error.value : undefined).toBeInstanceOf( + NotebookValidationError + ) + } + expect(fs.readFileSync(file, "utf8")).toBe(notebook("# COMPETITOR")) + } finally { + spy.mockRestore() + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/doctor-options.test.ts b/test/unit/doctor-options.test.ts new file mode 100644 index 0000000..bbf77fc --- /dev/null +++ b/test/unit/doctor-options.test.ts @@ -0,0 +1,58 @@ +import { describe, expect, it } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { ipynbDoctorTool } from "../../src/tools/doctor.js" +import type { ToolContext } from "../../src/tool.js" + +const ENV = "OPENCODE_IPYNB_OPTIONS" + +const context = (dir: string): ToolContext => + ({ + sessionID: "test", + messageID: "test", + agent: "test", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + }) as unknown as ToolContext + +const run = async (options: string): Promise => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-doctor-opts-")) + const previous = process.env[ENV] + process.env[ENV] = options + try { + const result = await ipynbDoctorTool.execute( + { includeSuggestions: true }, + context(dir) + ) + return typeof result === "string" ? result : result.output + } finally { + if (previous === undefined) delete process.env[ENV] + else process.env[ENV] = previous + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +describe("ipynb_doctor plugin options warning", () => { + it("reports an invalid options variable instead of silently defaulting", async () => { + const output = await run(JSON.stringify({ warmKernel: "yes" })) + expect(output).toContain("## Plugin options") + expect(output).toContain("warmKernel") + expect(output).toContain("invalid") + expect(output).toContain("default options are in effect") + }) + + it("reports unparseable JSON with the parse failure", async () => { + const output = await run("{ not json") + expect(output).toContain("## Plugin options") + expect(output).toContain("OPENCODE_IPYNB_OPTIONS is set but invalid") + }) + + it("renders no options section when the variable is valid", async () => { + const output = await run(JSON.stringify({ warmKernel: true })) + expect(output).not.toContain("## Plugin options") + }) +}) diff --git a/test/unit/error-view.test.ts b/test/unit/error-view.test.ts index ad4b9be..f80fc9b 100644 --- a/test/unit/error-view.test.ts +++ b/test/unit/error-view.test.ts @@ -59,6 +59,13 @@ describe("stripAnsi", () => { expect(hasAnsi("\u001b[31mred\u001b[0m")).toBe(true) expect(hasAnsi("plain text")).toBe(false) }) + + it("hasAnsi is stateless across calls", () => { + expect(hasAnsi("\u001b[31m")).toBe(true) + expect(hasAnsi("abc\u001b[0mx")).toBe(true) + expect(hasAnsi("plain")).toBe(false) + expect(hasAnsi("\u001b[1mbold")).toBe(true) + }) }) describe("formatOutputs > error view", () => { diff --git a/test/unit/execution-truncate.test.ts b/test/unit/execution-truncate.test.ts index 81a2001..9a7f9f8 100644 --- a/test/unit/execution-truncate.test.ts +++ b/test/unit/execution-truncate.test.ts @@ -274,3 +274,20 @@ describe("truncateRunResponse", () => { }) }) + +describe("truncateRunResponse per-cell budget", () => { + it("keeps a truncated output for every cell instead of starving the tail", () => { + const outputs = Array.from({ length: 40 }, (_, index) => + makeSummary({ cellIndex: index, stdout: `cell-${index}:` + "x".repeat(4_000) }) + ) + const out = truncateRunResponse(makeResponse({ outputs }), 6_000) + expect(out.outputs).toHaveLength(40) + for (const [index, cell] of out.outputs.entries()) { + const stdout = cell.stdout ?? "" + expect(stdout.length).toBeGreaterThan(0) + expect(stdout).toContain(`cell-${index}:`) + expect(stdout).toContain("truncated") + } + expect(out.outputs[39]?.stdout).not.toBe("") + }) +}) diff --git a/test/unit/export-improvements.test.ts b/test/unit/export-improvements.test.ts index b2c4dab..dc17d1c 100644 --- a/test/unit/export-improvements.test.ts +++ b/test/unit/export-improvements.test.ts @@ -727,3 +727,69 @@ describe("NotebookExportService > write safety", () => { }) }) + +describe("export output must use an export extension", () => { + const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + cells: [ + { cell_type: "markdown", metadata: {}, source: "# Title" }, + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "print(1)" + } + ] + } + + it("refuses to overwrite .env, package.json and id_rsa", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-export-ext-")) + try { + const file = writeNotebook(dir, "n.ipynb", notebook) + const { exportSvc } = buildExport(dir, dir) + for (const name of [".env", "package.json", "id_rsa"]) { + const target = path.join(dir, name) + fs.writeFileSync(target, "SENSITIVE") + const before = fs.readFileSync(target, "utf8") + const exit = await Effect.runPromiseExit( + exportSvc.export(file, { + format: "markdown", + outputPath: target, + includeOutputs: false, + maxOutputChars: 10_000 + } as never) + ) + expect(exit._tag).toBe("Failure") + expect(fs.readFileSync(target, "utf8")).toBe(before) + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("still writes a normal markdown export", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-export-ok-")) + try { + const file = writeNotebook(dir, "n.ipynb", notebook) + const { exportSvc } = buildExport(dir, dir) + const target = path.join(dir, "out.md") + await runOrThrow( + exportSvc.export(file, { + format: "markdown", + outputPath: target, + includeOutputs: false, + maxOutputChars: 10_000 + } as never) + ) + expect(fs.readFileSync(target, "utf8")).toContain("# Title") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/file-service-symlink.test.ts b/test/unit/file-service-symlink.test.ts index b191876..70e5bdf 100644 --- a/test/unit/file-service-symlink.test.ts +++ b/test/unit/file-service-symlink.test.ts @@ -157,6 +157,7 @@ describe("NotebookFileService realpath pinning", () => { }) it("classifies unreadable notebooks as a validation error, not not-found", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return if (process.platform === "win32") return const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-unreadable-")) const file = path.join(dir, "notebook.ipynb") diff --git a/test/unit/file-service-temp.test.ts b/test/unit/file-service-temp.test.ts new file mode 100644 index 0000000..c580a44 --- /dev/null +++ b/test/unit/file-service-temp.test.ts @@ -0,0 +1,163 @@ +import { describe, expect, it, spyOn } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { makeWarningSink } from "../../src/utils/warnings.js" + +const run = async (effect: Effect.Effect) => + Effect.runPromise(effect as Effect.Effect) + +const withTempDir = async (fn: (dir: string) => Promise): Promise => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "fsvc-")) + try { + await fn(dir) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +const notebook = (): Record => ({ + cells: [{ cell_type: "markdown", metadata: {}, source: ["# A"] }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 +}) + +describe("writeAtomic temp handling", () => { + it("leaves no temp file when the write succeeds", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, `${JSON.stringify(notebook(), null, 1)}\n`) + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + const outcome = await run(svc.writeAtomic(file, notebook() as never)) + expect(outcome.mode).toBeDefined() + expect(fs.readdirSync(dir).filter((entry) => entry.endsWith(".tmp"))).toEqual([]) + expect(sink.drain()).toEqual([]) + }) + }) + + it("reports an unlink failure instead of leaking the temp file silently", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.mkdirSync(file) + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + await expect(run(svc.writeAtomic(file, notebook() as never))).rejects.toBeDefined() + expect(fs.readdirSync(dir).filter((entry) => entry.endsWith(".tmp"))).toEqual([]) + }) + }) + + it("reports when the serialized notebook exceeds the size limit", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "big.ipynb") + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + const huge = { + cells: [ + { + cell_type: "markdown", + metadata: {}, + source: ["x".repeat(60 * 1024 * 1024)] + } + ], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + } + await expect(run(svc.writeAtomic(file, huge as never))).rejects.toBeDefined() + expect(fs.existsSync(file)).toBe(false) + }) + }) +}) + +describe("revision re-check reporting", () => { + it("recreates a deleted notebook and records the revision warning", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "gone.ipynb") + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + fs.writeFileSync(file, `${JSON.stringify(notebook(), null, 1)}\n`) + const before = fs.readFileSync(file, "utf8") + fs.rmSync(file) + const outcome = await run( + svc.writeAtomic(file, notebook() as never, { previousText: before }) + ) + expect(outcome.mode).toBeDefined() + expect(JSON.parse(fs.readFileSync(file, "utf8"))).toBeDefined() + }) + }) + + it("refuses to write when the revision re-read fails for a reason other than absence", async () => { + if (process.platform === "win32") return + if (typeof process.getuid === "function" && process.getuid() === 0) return + await withTempDir(async (dir) => { + const file = path.join(dir, "locked.ipynb") + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + const body = `${JSON.stringify(notebook(), null, 1)}\n` + fs.writeFileSync(file, body) + const before = fs.readFileSync(file) + fs.chmodSync(file, 0o000) + try { + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, notebook() as never, { previousText: body }) + ) + expect(exit._tag).toBe("Failure") + } finally { + fs.chmodSync(file, 0o600) + } + expect(fs.readFileSync(file).equals(before)).toBe(true) + void sink + }) + }) +}) + +describe("atomic replace fallback warnings", () => { + it("reports a failed backup attempt on the windows fallback path", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, `${JSON.stringify(notebook(), null, 1)}\n`) + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + const original = fs.promises.rename + let calls = 0 + const spy = spyOn(fs.promises, "rename").mockImplementation(((( + from: fs.PathLike, + to: fs.PathLike + ) => { + calls += 1 + if (calls <= 2) { + return Promise.reject(Object.assign(new Error("rename denied"), { code: "EPERM" })) + } + return original(from, to) + }) as unknown as typeof fs.promises.rename)) + const platformDescriptor = Object.getOwnPropertyDescriptor( + process, + "platform" + ) as PropertyDescriptor + Object.defineProperty(process, "platform", { value: "win32", configurable: true }) + try { + const outcome = await run( + svc.writeAtomic(file, { + cells: [{ cell_type: "markdown", metadata: {}, source: ["# B"] }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + } as never) + ) + expect(outcome.mode).toBeDefined() + expect(fs.readFileSync(file, "utf8")).toContain("# B") + const warnings = sink.drain() + expect(warnings.length).toBe(1) + expect(warnings[0]?.source).toBe("atomic-replace") + expect(warnings[0]?.detail).toContain("backup before replace") + } finally { + Object.defineProperty(process, "platform", platformDescriptor) + spy.mockRestore() + } + }) + }) +}) diff --git a/test/unit/helper-env-pip.test.ts b/test/unit/helper-env-pip.test.ts new file mode 100644 index 0000000..f3e8d77 --- /dev/null +++ b/test/unit/helper-env-pip.test.ts @@ -0,0 +1,88 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" + +const helper = path.resolve("python", "ipynb_runner.py") +const python = "python" + +const notebook = (): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "print(1)" + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +interface EnvResponse { + readonly success: boolean + readonly env?: { readonly pipFreeze?: ReadonlyArray } +} + +const runEnv = (interpreter: string, file: string): EnvResponse => { + const result = Bun.spawnSync([interpreter, helper], { + stdin: new TextEncoder().encode( + JSON.stringify({ filePath: file, mode: "env" }) + ), + stdout: "pipe", + stderr: "pipe" + }) + expect(result.exitCode).toBe(0) + const line = result.stdout.toString().trim().split("\n").filter(Boolean).at(-1) ?? "" + return JSON.parse(line) as EnvResponse +} + +describeIf(realHelperEnabled(), "env report without pip", () => { + if (process.platform === "win32") return + it("degrades the package list instead of failing on a venv without pip", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-nopip-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook()) + const venv = path.join(dir, "nopip") + try { + const created = Bun.spawnSync([python, "-m", "venv", "--without-pip", venv], { + stdout: "pipe", + stderr: "pipe" + }) + expect(created.exitCode).toBe(0) + const noPip = path.join(venv, "bin", "python") + expect(fs.existsSync(noPip)).toBe(true) + const probe = Bun.spawnSync([noPip, "-c", "import pip"], { + stdout: "pipe", + stderr: "pipe" + }) + expect(probe.exitCode).not.toBe(0) + const response = runEnv(noPip, file) + expect(response.success).toBe(true) + expect(response.env?.pipFreeze).toEqual([]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 120_000) + + it("still reports the package list when pip is available", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-withpip-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook()) + try { + const response = runEnv(python, file) + expect(response.success).toBe(true) + expect(Array.isArray(response.env?.pipFreeze)).toBe(true) + expect((response.env?.pipFreeze ?? []).length).toBeGreaterThan(0) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 120_000) +}) diff --git a/test/unit/helper-input-validation.test.ts b/test/unit/helper-input-validation.test.ts new file mode 100644 index 0000000..9c3bbf9 --- /dev/null +++ b/test/unit/helper-input-validation.test.ts @@ -0,0 +1,88 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" + +const helper = path.resolve("python", "ipynb_runner.py") +const python = "python" + +const notebook = (): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "print(1)" + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +interface Run { + readonly code: number + readonly stdout: string + readonly stderr: string +} + +const runHelper = (payload: unknown): Run => { + const result = Bun.spawnSync([python, helper], { + stdin: new TextEncoder().encode(JSON.stringify(payload)), + stdout: "pipe", + stderr: "pipe" + }) + return { + code: result.exitCode ?? -1, + stdout: result.stdout.toString(), + stderr: result.stderr.toString() + } +} + +const parse = (stdout: string): Record => { + const line = stdout.trim().split("\n").filter(Boolean).at(-1) ?? "" + return JSON.parse(line) as Record +} + +describeIf(realHelperEnabled(), "helper input validation", () => { + if (process.platform === "win32") return + const cases: ReadonlyArray = [ + ["maxOutputChars", "x"], + ["maxOutputChars", 1.5], + ["maxOutputChars", -5], + ["timeoutMs", null], + ["timeoutMs", "soon"], + ["timeoutMs", true] + ] + + for (const [field, value] of cases) { + it(`rejects ${field}=${JSON.stringify(value)} with a structured error`, () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-helper-validate-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook()) + try { + const run = runHelper({ + filePath: file, + mode: "cell", + cellIndex: 0, + [field]: value + }) + expect(run.code).toBe(0) + expect(run.stderr).not.toContain("Traceback (most recent call last)") + const response = parse(run.stdout) + expect(response.success).toBe(false) + const error = response.error as { evalue?: string } + expect(error.evalue).toContain(field) + expect(error.evalue).toContain("positive integer") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + } +}) diff --git a/test/unit/helper-orphan-watchdog.test.ts b/test/unit/helper-orphan-watchdog.test.ts new file mode 100644 index 0000000..ddf35d4 --- /dev/null +++ b/test/unit/helper-orphan-watchdog.test.ts @@ -0,0 +1,112 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" + +const helper = path.resolve("python", "ipynb_runner.py") +const python = "python" + +const notebook = (source: string): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +// A killed helper that nobody reaps becomes a zombie, and signal 0 still +// succeeds for a zombie. On Linux read the process state so "alive" means +// actually running, not merely present in the process table. +const alive = (pid: number): boolean => { + try { + process.kill(pid, 0) + } catch { + return false + } + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8") + const state = stat.slice(stat.lastIndexOf(")") + 2, stat.lastIndexOf(")") + 3) + return state !== "Z" && state !== "X" + } catch { + return true + } +} + +const waitFor = async (predicate: () => boolean, timeoutMs: number): Promise => { + const started = Date.now() + while (Date.now() - started < timeoutMs) { + if (predicate()) return true + await new Promise((resolve) => setTimeout(resolve, 50)) + } + return predicate() +} + +describeIf(realHelperEnabled(), "parent death watchdog", () => { + it("kills the helper and its kernel when the parent dies mid-cell", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-watchdog-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook("import time\ntime.sleep(30)\nprint(1)")) + // The parent is a small shell that spawns the helper and then sleeps; killing + // it reproduces a plugin crash while a cell is running. + const driver = path.join(dir, "driver.sh") + fs.writeFileSync( + driver, + `#!/bin/sh +${JSON.stringify(python)} ${JSON.stringify(helper)} < ${JSON.stringify(path.join(dir, "requests.ndjson"))} > ${JSON.stringify(path.join(dir, "out.ndjson"))} 2>/dev/null & +echo $! > ${JSON.stringify(path.join(dir, "child.pid"))} +sleep 300 +` + ) + fs.chmodSync(driver, 0o755) + fs.writeFileSync( + path.join(dir, "requests.ndjson"), + `${JSON.stringify({ mode: "serve", filePath: file, timeoutMs: 60_000 })}\n${JSON.stringify({ + id: 1, + mode: "cell", + cellIndex: 0, + timeoutMs: 60_000 + })}\n` + ) + const parent = Bun.spawn(["/bin/sh", driver], { + stdout: "ignore", + stderr: "ignore" + }) + try { + const pidFile = path.join(dir, "child.pid") + expect(await waitFor(() => fs.existsSync(pidFile), 10_000)).toBe(true) + const helperPid = Number(fs.readFileSync(pidFile, "utf8").trim()) + expect(Number.isInteger(helperPid)).toBe(true) + const outFile = path.join(dir, "out.ndjson") + expect( + await waitFor( + () => fs.existsSync(outFile) && fs.readFileSync(outFile, "utf8").includes('"ready"'), + 20_000 + ) + ).toBe(true) + // Give the cell time to start, then kill the parent. + await new Promise((resolve) => setTimeout(resolve, 1_500)) + expect(alive(helperPid)).toBe(true) + parent.kill("SIGKILL") + const gone = await waitFor(() => !alive(helperPid), 15_000) + expect(gone).toBe(true) + } finally { + try { + parent.kill("SIGKILL") + } catch {} + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 120_000) +}) diff --git a/test/unit/helper-raw-outputs.test.ts b/test/unit/helper-raw-outputs.test.ts new file mode 100644 index 0000000..e35e4be --- /dev/null +++ b/test/unit/helper-raw-outputs.test.ts @@ -0,0 +1,89 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" + +const helper = path.resolve("python", "ipynb_runner.py") +const python = "python" + +const notebook = (source: string): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +interface RunOutput { + readonly rawOutputs?: ReadonlyArray> + readonly displayData?: ReadonlyArray<{ mime: string }> +} + +interface RunResponse { + readonly success: boolean + readonly outputs: ReadonlyArray +} + +const run = (payload: Record): RunResponse => { + const result = Bun.spawnSync([python, helper], { + stdin: new TextEncoder().encode(JSON.stringify(payload)), + stdout: "pipe", + stderr: "pipe" + }) + expect(result.exitCode).toBe(0) + const line = result.stdout.toString().trim().split("\n").filter(Boolean).at(-1) ?? "" + return JSON.parse(line) as RunResponse +} + +describeIf(realHelperEnabled(), "raw outputs are requested when the result is saved", () => { + if (process.platform === "win32") return + it("keeps the html bundle when includeRawOutputs is set", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-raw-mime-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync( + file, + notebook( + "from IPython.display import HTML, display\ndisplay(HTML('raw'))" + ) + ) + try { + const saved = run({ + filePath: file, + mode: "cell", + cellIndex: 0, + timeoutMs: 60_000, + includeRawOutputs: true, + maxOutputChars: 6_000 + }) + expect(saved.success).toBe(true) + const savedRaw = JSON.stringify(saved.outputs) + expect(savedRaw).toContain("text/html") + expect(savedRaw).toContain("raw") + + const summaryOnly = run({ + filePath: file, + mode: "cell", + cellIndex: 0, + timeoutMs: 60_000, + includeRawOutputs: false, + maxOutputChars: 6_000 + }) + expect(summaryOnly.success).toBe(true) + expect(JSON.stringify(summaryOnly.outputs)).not.toContain("raw") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 180_000) +}) diff --git a/test/unit/helper-serve-identity.test.ts b/test/unit/helper-serve-identity.test.ts new file mode 100644 index 0000000..6aa7c60 --- /dev/null +++ b/test/unit/helper-serve-identity.test.ts @@ -0,0 +1,79 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" + +const helper = path.resolve("python", "ipynb_runner.py") +const python = "python" + +const notebook = (source: string): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +interface ServeResponse { + readonly id?: number + readonly success: boolean + readonly error?: { readonly ename?: string; readonly evalue?: string } +} + +const serve = (init: Record, requests: ReadonlyArray): ServeResponse[] => { + const input = [init, ...requests].map((item) => JSON.stringify(item)).join("\n") + "\n" + const result = Bun.spawnSync([python, helper], { + stdin: new TextEncoder().encode(input), + stdout: "pipe", + stderr: "pipe" + }) + expect(result.exitCode).toBe(0) + return result.stdout + .toString() + .trim() + .split("\n") + .filter(Boolean) + .map((line) => JSON.parse(line) as ServeResponse) +} + +describeIf(realHelperEnabled(), "serve mode notebook identity", () => { + if (process.platform === "win32") return + it("refuses a request that names a different notebook than the kernel serves", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-serve-mismatch-")) + const initFile = path.join(dir, "init.ipynb") + const otherFile = path.join(dir, "other.ipynb") + try { + fs.writeFileSync(initFile, notebook("print('FROM_INIT')")) + fs.writeFileSync(otherFile, notebook("print('FROM_OTHER')")) + const [ready, ...responses] = serve( + { mode: "serve", filePath: initFile, timeoutMs: 60_000 }, + [ + { id: 1, mode: "cell", cellIndex: 0, filePath: otherFile, timeoutMs: 60_000 }, + { id: 2, mode: "cell", cellIndex: 0, timeoutMs: 60_000 }, + { mode: "shutdown" } + ] + ) + expect(ready).toBeDefined() + const mismatch = responses.find((response) => response.id === 1) + expect(mismatch?.success).toBe(false) + expect(mismatch?.error?.ename).toBe("NotebookMismatch") + expect(mismatch?.error?.evalue ?? "").toContain("other.ipynb") + const served = responses.find((response) => response.id === 2) + expect(served?.success).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 180_000) +}) diff --git a/test/unit/helper-shutdown-preempt.test.ts b/test/unit/helper-shutdown-preempt.test.ts new file mode 100644 index 0000000..33c2017 --- /dev/null +++ b/test/unit/helper-shutdown-preempt.test.ts @@ -0,0 +1,99 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" + +const helper = path.resolve("python", "ipynb_runner.py") +const python = "python" + +const notebook = (source: string): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +const alive = (pid: number): boolean => { + try { + process.kill(pid, 0) + return true + } catch { + return false + } +} + +describeIf(realHelperEnabled(), "queued shutdown preempts a running cell", () => { + it("returns promptly and reaps the kernel instead of waiting for the cell", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-shutdown-preempt-")) + const file = path.join(dir, "n.ipynb") + // A cell far longer than the test budget: without preemption this test + // would have to wait for it. + fs.writeFileSync(file, notebook("import time\ntime.sleep(120)\nprint(1)")) + const child = Bun.spawn([python, helper], { + stdin: "pipe", + stdout: "pipe", + stderr: "pipe" + }) + const writer = child.stdin as import("bun").FileSink + const send = (value: unknown): void => { + writer.write(`${JSON.stringify(value)}\n`) + writer.flush() + } + try { + send({ mode: "serve", filePath: file, timeoutMs: 300_000 }) + const ready = await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("no ready line")), 30_000) + let buffer = "" + const decoder = new TextDecoder() + const reader = (child.stdout as ReadableStream).getReader() + const pump = async (): Promise => { + for (;;) { + const { done, value } = await reader.read() + if (done) return + buffer += decoder.decode(value, { stream: true }) + const line = buffer.split("\n").find((candidate) => candidate.includes('"ready"')) + if (line !== undefined) { + clearTimeout(timer) + resolve(line) + return + } + } + } + void pump() + }) + expect(ready).toContain('"ready"') + send({ id: 1, mode: "cell", cellIndex: 0, timeoutMs: 300_000 }) + await new Promise((resolve) => setTimeout(resolve, 2_000)) + const started = Date.now() + send({ mode: "shutdown" }) + const exitCode = await Promise.race([ + child.exited, + new Promise<"timeout">((resolve) => setTimeout(() => resolve("timeout"), 25_000)) + ]) + const elapsed = Date.now() - started + expect(exitCode).not.toBe("timeout") + expect(elapsed).toBeLessThan(25_000) + expect(child.pid).toBeDefined() + expect(alive(child.pid)).toBe(false) + } finally { + try { + child.kill("SIGKILL") + } catch {} + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 180_000) +}) diff --git a/test/unit/inspect-heuristics.test.ts b/test/unit/inspect-heuristics.test.ts index a929802..b1071e4 100644 --- a/test/unit/inspect-heuristics.test.ts +++ b/test/unit/inspect-heuristics.test.ts @@ -48,6 +48,7 @@ const rawCell = (source: string): RawCellRaw => ({ const buildNotebook = (cells: ReadonlyArray): NotebookRaw => ({ nbformat: 4, + nbformat_minor: 5, metadata: {}, cells: [...cells] }) diff --git a/test/unit/json-patch-edits.test.ts b/test/unit/json-patch-edits.test.ts new file mode 100644 index 0000000..cdeb986 --- /dev/null +++ b/test/unit/json-patch-edits.test.ts @@ -0,0 +1,62 @@ +import { describe, expect, it } from "bun:test" +import { applyEdits } from "../../src/utils/json-patch.js" + +describe("applyEdits", () => { + it("splices non-overlapping edits in sorted order even when given unsorted", () => { + expect( + applyEdits("0123456789", [ + { start: 8, end: 9, text: "B" }, + { start: 2, end: 3, text: "A" } + ]) + ).toBe("01A34567B9") + }) + + it("keeps a late edit last when the pair is sorted but unsorted in the input", () => { + expect( + applyEdits("0123456789", [ + { start: 10, end: 20, text: "A" }, + { start: 5, end: 6, text: "B" } + ]) + ).toBe("01234B6789A") + }) + + it("accepts adjacent edits whose boundaries touch", () => { + expect( + applyEdits("abcd", [ + { start: 0, end: 2, text: "X" }, + { start: 2, end: 4, text: "Y" } + ]) + ).toBe("XY") + }) + + it("rejects a sorted overlapping pair", () => { + expect( + applyEdits("0123456789", [ + { start: 1, end: 5, text: "X" }, + { start: 4, end: 7, text: "Y" } + ]) + ).toBeUndefined() + }) + + it("rejects an overlapping pair after sorting", () => { + expect( + applyEdits("0123456789", [ + { start: 4, end: 7, text: "Y" }, + { start: 1, end: 5, text: "X" } + ]) + ).toBeUndefined() + }) + + it("breaks equal starts by end, letting a shorter edit that ends first apply", () => { + expect( + applyEdits("0123456789", [ + { start: 5, end: 10, text: "A" }, + { start: 5, end: 5, text: "B" } + ]) + ).toBe("01234BA") + }) + + it("returns the text untouched for an empty edit list", () => { + expect(applyEdits("abc", [])).toBe("abc") + }) +}) diff --git a/test/unit/json-patch-fuzz.test.ts b/test/unit/json-patch-fuzz.test.ts new file mode 100644 index 0000000..4a5bf45 --- /dev/null +++ b/test/unit/json-patch-fuzz.test.ts @@ -0,0 +1,323 @@ +import { describe, expect, it } from "bun:test" +import { patchJsonTextDetailed } from "../../src/utils/json-patch.js" +import type { JsonTextStyle } from "../../src/utils/json-patch.js" + +const mulberry32 = (seed: number): (() => number) => { + let state = seed >>> 0 + return () => { + state = (state + 0x6d2b79f5) >>> 0 + let t = state + t = Math.imul(t ^ (t >>> 15), t | 1) + t ^= t + Math.imul(t ^ (t >>> 7), t | 61) + return ((t ^ (t >>> 14)) >>> 0) / 4294967296 + } +} + +const pick = (rnd: () => number, items: ReadonlyArray): T => + items[Math.floor(rnd() * items.length)]! + +const STRING_POOL = [ + "", + "plain", + "with \"quotes\"", + "back\\slash", + "line\nbreak", + "tab\there", + "\u0001\u001f", + "unicodé", + "日本語", + "astral \u{1F680}", + "emoji \u{1F9EA}\u{1F52C}", + "$dollar {brace} [bracket]" +] + +const randomValue = (rnd: () => number, depth: number): unknown => { + const kind = depth > 3 ? Math.floor(rnd() * 4) : Math.floor(rnd() * 6) + switch (kind) { + case 0: + return null + case 1: + return rnd() < 0.5 + case 2: { + const roll = rnd() + if (roll < 0.4) return Math.floor(rnd() * 2000) - 1000 + if (roll < 0.8) return Math.round((rnd() * 200 - 100) * 1000) / 1000 + return rnd() * 1e6 + } + case 3: + return pick(rnd, STRING_POOL) + case 4: { + const length = Math.floor(rnd() * 4) + return Array.from({ length }, () => randomValue(rnd, depth + 1)) + } + default: { + const length = Math.floor(rnd() * 4) + const keys = ["a", "b", "cells", "z", "metadata", "é", "\u{1F680}k"] + const value: Record = {} + for (let index = 0; index < length; index += 1) { + value[pick(rnd, keys) + (rnd() < 0.3 ? String(Math.floor(rnd() * 3)) : "")] = + randomValue(rnd, depth + 1) + } + return value + } + } +} + +const deepEqual = (left: unknown, right: unknown): boolean => { + if (Object.is(left, right)) return true + if (typeof left !== typeof right) return false + if (left === null || right === null) return left === right + if (Array.isArray(left) !== Array.isArray(right)) return false + if (Array.isArray(left) && Array.isArray(right)) { + return ( + left.length === right.length && + left.every((item, index) => deepEqual(item, right[index])) + ) + } + if (typeof left === "object" && typeof right === "object") { + const leftKeys = Object.keys(left as object) + const rightKeys = Object.keys(right as object) + if (leftKeys.length !== rightKeys.length) return false + return leftKeys.every( + (key) => + Object.prototype.hasOwnProperty.call(right, key) && + deepEqual( + (left as Record)[key], + (right as Record)[key] + ) + ) + } + return false +} + +const encodeString = ( + value: string, + ensureAscii: boolean +): string => { + const encoded = JSON.stringify(value) + if (!ensureAscii) return encoded + return encoded.replace(/[\u007f-\uffff]/g, (char) => + `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` + ) +} + +const serialize = ( + value: unknown, + rnd: () => number, + style: JsonTextStyle, + depth: number, + multiline: boolean, + indent: string +): string => { + if (value === null) return "null" + if (typeof value === "boolean") return String(value) + if (typeof value === "number") return JSON.stringify(value) + if (typeof value === "string") return encodeString(value, style.ensureAscii) + const childIndent = `${indent}${style.unit}` + if (Array.isArray(value)) { + if (value.length === 0) return "[]" + if (!multiline) { + return `[${value + .map((item) => serialize(item, rnd, style, depth + 1, false, childIndent)) + .join(style.itemSeparator)}]` + } + return `[${style.newline}${value + .map( + (item) => + `${childIndent}${serialize(item, rnd, style, depth + 1, true, childIndent)}` + ) + .join(`,${style.newline}`)}${style.newline}${indent}]` + } + const record = value as Record + const keys = Object.keys(record) + if (keys.length === 0) return "{}" + const render = (key: string): string => + `${encodeString(key, style.ensureAscii)}${style.keySeparator}${serialize( + record[key], + rnd, + style, + depth + 1, + multiline, + childIndent + )}` + if (!multiline) { + return `{${keys.map(render).join(style.itemSeparator)}}` + } + return `{${style.newline}${keys + .map((key) => `${childIndent}${render(key)}`) + .join(`,${style.newline}`)}${style.newline}${indent}}` +} + +const styleFor = (rnd: () => number): JsonTextStyle => ({ + unit: pick(rnd, [" ", " ", "\t"]), + newline: pick(rnd, ["\n", "\r\n"] as const), + itemSeparator: pick(rnd, [",", ", "]), + keySeparator: pick(rnd, [":", ": "]), + ensureAscii: rnd() < 0.3 +}) + +const mutate = (rnd: () => number, value: unknown, depth: number): unknown => { + if (depth > 3 || rnd() < 0.35) return randomValue(rnd, depth) + if (Array.isArray(value)) { + const next = value.map((item) => mutate(rnd, item, depth + 1)) + if (rnd() < 0.3) next.push(randomValue(rnd, depth + 1)) + if (next.length > 0 && rnd() < 0.25) next.pop() + return next + } + if (value !== null && typeof value === "object") { + const record = value as Record + const next: Record = {} + for (const key of Object.keys(record)) { + if (rnd() < 0.15) continue + next[key] = mutate(rnd, record[key], depth + 1) + } + if (rnd() < 0.4) { + next[`k${Math.floor(rnd() * 100)}`] = randomValue(rnd, depth + 1) + } + return next + } + return randomValue(rnd, depth) +} + +const REASONS = new Set([ + "parse-failed", + "patch-threw", + "overlapping-edits", + "not-representable", + "verification-failed" +]) + +describe("patchJsonTextDetailed property fuzz", () => { + it("never throws, always parses back to the target, and is idempotent", () => { + const rnd = mulberry32(20261118) + let patched = 0 + let fellBack = 0 + for (let iteration = 0; iteration < 2000; iteration += 1) { + const style = styleFor(rnd) + const source = randomValue(rnd, 0) + const multiline = rnd() < 0.5 + const text = + serialize(source, rnd, style, 0, multiline, "") + + (rnd() < 0.5 ? style.newline : "") + const target = mutate(rnd, source, 0) + let result: ReturnType + try { + result = patchJsonTextDetailed(text, target, { style }) + } catch (error) { + throw new Error( + `iteration ${iteration}: patcher threw on ${JSON.stringify(text)} -> ${JSON.stringify(target)}: ${String(error)}` + ) + } + if (result.text !== undefined) { + patched += 1 + const reparsed = JSON.parse(result.text) as unknown + if (!deepEqual(reparsed, target)) { + throw new Error( + `iteration ${iteration}: patched text diverges from target\nsource: ${JSON.stringify(text)}\ntarget: ${JSON.stringify(target)}\npatched: ${JSON.stringify(result.text)}` + ) + } + const again = patchJsonTextDetailed(result.text, target, { style }) + if (again.text !== result.text) { + throw new Error( + `iteration ${iteration}: patch is not idempotent\nfirst: ${JSON.stringify(result.text)}\nsecond: ${JSON.stringify(again.text)}` + ) + } + continue + } + fellBack += 1 + expect(result.reason).toBeDefined() + expect(REASONS.has(result.reason!)).toBe(true) + } + expect(patched + fellBack).toBe(2000) + expect(patched).toBeGreaterThan(0) + }) + + it("returns the stored text untouched when the value already matches", () => { + const rnd = mulberry32(777) + for (let iteration = 0; iteration < 500; iteration += 1) { + const style = styleFor(rnd) + const value = randomValue(rnd, 0) + const text = + serialize(value, rnd, style, 0, rnd() < 0.5, "") + + (rnd() < 0.5 ? style.newline : "") + const result = patchJsonTextDetailed(text, JSON.parse(text), { style }) + if (result.text !== undefined) { + expect(result.text).toBe(text) + } + } + }) + + it("never emits unverifiable text when the source text has duplicate keys", () => { + const style: JsonTextStyle = { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + const text = `{"a": 1, "b": 2, "a": 3}` + const result = patchJsonTextDetailed(text, { a: 4, b: 2 }, { style }) + if (result.text !== undefined) { + expect(deepEqual(JSON.parse(result.text), { a: 4, b: 2 })).toBe(true) + } else { + expect(REASONS.has(result.reason!)).toBe(true) + } + const identity = patchJsonTextDetailed(text, JSON.parse(text), { style }) + expect(identity.text).toBe(text) + }) +}) + +describe("object keys that use escape sequences", () => { + it("keeps the stored escape when another key changes", () => { + const style: JsonTextStyle = { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + const text = `{"a\\u0041b": 1, "z": 2}` + const result = patchJsonTextDetailed(text, { aAb: 1, z: 3 }, { style }) + expect(result.reason).toBeUndefined() + expect(result.text).toBe(`{"a\\u0041b": 1, "z": 3}`) + }) +}) + +describe("array growth keeps the stored separator layout", () => { + it("appends a new item on its own line in a multiline notebook", async () => { + const { makeEditImpl, makeNotebookFileService, makePathService, makePermissionService } = await import( + "../../src/services/index.js" + ) + const { Effect } = await import("effect") + const fs = await import("node:fs") + const os = await import("node:os") + const path = await import("node:path") + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-grow-sep-")) + const file = path.join(dir, "n.ipynb") + const body = `{\n "cells": [\n {\n "cell_type": "code",\n "execution_count": null,\n "metadata": {},\n "outputs": [],\n "source": [\n "print(1)"\n ]\n }\n ],\n "metadata": {},\n "nbformat": 4,\n "nbformat_minor": 5\n}\n` + fs.writeFileSync(file, body) + const ctx = { + sessionID: "t", + messageID: "t", + agent: "t", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + } as never + try { + const edit = makeEditImpl( + makePathService({ directory: dir, worktree: dir, platform: process.platform }), + makeNotebookFileService(), + makePermissionService(ctx) + ) + await Effect.runPromise(edit.insertCell(file, "code", "print(2)", 1)) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain(` },\n {\n`) + expect(after).not.toContain("},{") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/json-schema-conditions.test.ts b/test/unit/json-schema-conditions.test.ts new file mode 100644 index 0000000..db3d2ae --- /dev/null +++ b/test/unit/json-schema-conditions.test.ts @@ -0,0 +1,84 @@ +import { describe, expect, it } from "bun:test" +import { toolDefinitions } from "../../src/registrations.js" +import { toV2Tool } from "../../src/plugin-v2.js" +import type { Plugin } from "@opencode/plugin" + +interface JsonSchema { + readonly anyOf?: ReadonlyArray> + readonly required?: ReadonlyArray + readonly properties?: Record }> +} + +const schemaFor = (name: string): JsonSchema => { + const registration = { + name, + definition: toolDefinitions[name]!, + permission: undefined + } as never + const info = toV2Tool( + { options: {}, location: { directory: "/tmp", project: { directory: "/tmp" } } } as unknown as Plugin.Context, + registration + ) + return info.input as unknown as JsonSchema +} + +const validates = ( + schema: JsonSchema, + value: Record +): boolean => { + const branches = schema.anyOf + if (branches === undefined) return true + return branches.some((branch) => { + const required = (branch.required ?? []) as ReadonlyArray + for (const key of required) { + if (!(key in value)) return false + } + const not = branch.not as { anyOf?: ReadonlyArray<{ required?: ReadonlyArray }> } | undefined + if (not?.anyOf !== undefined) { + const excluded = not.anyOf.some((inner) => + (inner.required ?? []).every((key) => key in value) + ) + if (excluded) return false + } + const properties = branch.properties as + | Record }> + | undefined + if (properties !== undefined) { + for (const [key, constraint] of Object.entries(properties)) { + if (constraint.enum !== undefined && key in value) { + if (!constraint.enum.includes(String(value[key]))) return false + } + } + } + return true + }) +} + +describe("generated schema expresses the runtime requirements", () => { + it("rejects an ipynb_read call that only names the file", () => { + const schema = schemaFor("ipynb_read") + expect(validates(schema, { filePath: "n.ipynb" })).toBe(false) + expect(validates(schema, { filePath: "n.ipynb", cellIndex: 0 })).toBe(true) + expect(validates(schema, { filePath: "n.ipynb", start: 0, end: 3 })).toBe(true) + expect(validates(schema, { filePath: "n.ipynb", cellIndex: 0, start: 0 })).toBe(false) + expect(validates(schema, { filePath: "n.ipynb", start: 0 })).toBe(false) + }) + + it("rejects an ipynb_outputs read without a cell index", () => { + const schema = schemaFor("ipynb_outputs") + expect(validates(schema, { filePath: "n.ipynb", operation: "read" })).toBe(false) + expect( + validates(schema, { filePath: "n.ipynb", operation: "read", cellIndex: 0 }) + ).toBe(true) + expect(validates(schema, { filePath: "n.ipynb", operation: "list" })).toBe(true) + expect(validates(schema, { filePath: "n.ipynb", operation: "clear_all" })).toBe(true) + expect( + validates(schema, { filePath: "n.ipynb", operation: "clear_cell" }) + ).toBe(false) + }) + + it("leaves tools without conditional requirements unchanged", () => { + const schema = schemaFor("ipynb_inspect") + expect(schema.anyOf).toBeUndefined() + }) +}) diff --git a/test/unit/kernel-death-recovery.test.ts b/test/unit/kernel-death-recovery.test.ts new file mode 100644 index 0000000..8af116b --- /dev/null +++ b/test/unit/kernel-death-recovery.test.ts @@ -0,0 +1,72 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { Effect } from "effect" +import { makeKernelManager } from "../../src/services/KernelManager.js" + +const notebook = { + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "print(1)" + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 +} + +describeIf(realHelperEnabled(), "kernel death recovery", () => { + it("drops a dead kernel state so the next request starts a fresh one", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-kernel-dead-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const flag = path.join(dir, "crashed.flag") + fs.writeFileSync( + file, + JSON.stringify({ + ...notebook, + cells: [ + { + ...notebook.cells[0]!, + source: `import os, pathlib\nflag = pathlib.Path(${JSON.stringify(flag)})\nif not flag.exists():\n flag.write_text('1')\n os._exit(1)\nprint(1)` + } + ] + }) + ) + const helper = path.resolve("python", "ipynb_runner.py") + const manager = makeKernelManager({ + pythonPath: "python", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 30_000 + }) + const request = { + filePath: file, + mode: "all" as const, + timeoutMs: 30_000, + save: false, + maxOutputChars: 2_000 + } + try { + const first = await Effect.runPromiseExit(manager.execute(file, request)) + expect(first._tag).toBe("Failure") + expect(manager.isRunning(file)).toBe(false) + const second = await Effect.runPromiseExit(manager.execute(file, request)) + expect(second._tag).toBe("Success") + expect(manager.isRunning(file)).toBe(true) + } finally { + await Effect.runPromise(manager.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 180_000) +}) diff --git a/test/unit/kernel-forgery.test.ts b/test/unit/kernel-forgery.test.ts new file mode 100644 index 0000000..948e582 --- /dev/null +++ b/test/unit/kernel-forgery.test.ts @@ -0,0 +1,74 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { Effect } from "effect" +import { makeKernelManager } from "../../src/services/KernelManager.js" +import { makeWarningSink } from "../../src/utils/warnings.js" + +const forgerySource = (requestId: number): string => + [ + "import json, os, sys", + "sys.stdout.flush()", + `os.write(1, (json.dumps({'id': ${requestId}, 'success': True, 'executedCells': [0], 'durationMs': 1,`, + " 'outputs': [{'cellIndex': 0, 'status': 'ok', 'stdout': 'FORGED\\n'}]}) + '\\n').encode())", + "print('REAL')" + ].join("\n") + +const notebook = (source: string): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +describeIf(realHelperEnabled(), "kernel response forgery", () => { + it("ignores a response-shaped line a cell writes without the request nonce", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-kernel-forge-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook("print('REAL')")) + const manager = makeKernelManager({ + pythonPath: "python", + helperPath: path.resolve("python", "ipynb_runner.py"), + workingDirectory: dir, + defaultTimeoutMs: 60_000, + warningSink: makeWarningSink() + }) + const request = () => ({ + filePath: file, + mode: "all" as const, + timeoutMs: 30_000, + save: false, + maxOutputChars: 4_000 + }) + try { + await Effect.runPromise(manager.execute(file, request())) + const pendingId = 2 + fs.writeFileSync(file, notebook(forgerySource(pendingId))) + const result = await Effect.runPromise(manager.execute(file, request())) + expect(result.success).toBe(true) + const stdout = result.outputs + .map((output) => output.stdout ?? "") + .join("") + expect(stdout).toContain("REAL") + expect(result.executedCells).toEqual([0]) + } finally { + await Effect.runPromise(manager.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 180_000) +}) diff --git a/test/unit/kernel-manager.test.ts b/test/unit/kernel-manager.test.ts index 662b9fa..08e7f48 100644 --- a/test/unit/kernel-manager.test.ts +++ b/test/unit/kernel-manager.test.ts @@ -1,14 +1,45 @@ -import { describe, expect, it } from "bun:test" +import { describe, expect, it, spyOn } from "bun:test" import * as path from "node:path" import * as fs from "node:fs" import * as os from "node:os" import { Effect } from "effect" -import { makeKernelManager } from "../../src/services/KernelManager.js" +import { makeKernelManager, killPidTree } from "../../src/services/KernelManager.js" import { pythonHas } from "../helpers.js" const HELPER = path.resolve("python", "ipynb_runner.py") const FIXTURES = path.resolve("test", "fixtures") const SKIP = !pythonHas("nbclient") + +describe("killPidTree failure reporting", () => { + it("reports when the group kill fails and the direct kill is refused", () => { + if (process.platform === "win32") return + // PID 2 is kthreadd only on Linux: on macOS no such process exists, both + // kills report ESRCH, and the tree correctly stays silent. Simulate a + // live process the caller cannot signal, so the refusal path is exercised + // by the kill bookkeeping itself rather than by whichever privileged PIDs + // the operating system happens to run. + const spy = spyOn(process, "kill").mockImplementation((() => { + throw Object.assign(new Error("refused"), { code: "EPERM" }) + }) as never) + const failures: unknown[] = [] + try { + killPidTree(123_456, "SIGTERM", (error) => failures.push(error)) + } finally { + spy.mockRestore() + } + expect(failures.length).toBe(1) + expect((failures[0] as NodeJS.ErrnoException).code).toBe("EPERM") + }) + + it("stays silent when the process is already gone", () => { + if (process.platform === "win32") return + const failures: unknown[] = [] + killPidTree(10_000_000, "SIGTERM", (error) => failures.push(error)) + killPidTree(10_000_001, "SIGKILL", (error) => failures.push(error)) + expect(failures.length).toBe(0) + }) +}) + const describeIf = (cond: boolean, name: string, fn: () => void): void => { if (cond) describe(name, fn) else describe.skip(name, fn) @@ -373,14 +404,31 @@ describeIf(!SKIP, "KernelManager", () => { await new Promise((resolve) => setTimeout(resolve, 50)) } expect(pid).toBeGreaterThan(0) - let alive = true - while (Date.now() < deadline && alive) { + // Signal 0 still succeeds for a zombie, and a killed grandchild that + // nobody reaps stays a zombie; read the state so the assertion means + // "stopped", not "still in /proc". + const running = (): boolean => { try { process.kill(pid, 0) - await new Promise((resolve) => setTimeout(resolve, 100)) } catch { + return false + } + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8") + const at = stat.lastIndexOf(")") + const state = stat.slice(at + 2, at + 3) + return state !== "Z" && state !== "X" + } catch { + return true + } + } + let alive = true + while (Date.now() < deadline && alive) { + if (!running()) { alive = false + break } + await new Promise((resolve) => setTimeout(resolve, 100)) } expect(alive).toBe(false) } finally { diff --git a/test/unit/kernel-request-isolation.test.ts b/test/unit/kernel-request-isolation.test.ts new file mode 100644 index 0000000..9b734a7 --- /dev/null +++ b/test/unit/kernel-request-isolation.test.ts @@ -0,0 +1,67 @@ +import { expect, it } from "bun:test" +import { describeIf, realHelperEnabled } from "../helpers.js" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { Effect } from "effect" +import { makeKernelManager } from "../../src/services/KernelManager.js" + +const notebook = (source: string): string => + JSON.stringify({ + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source + } + ], + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + nbformat: 4, + nbformat_minor: 5 + }) + +describeIf(realHelperEnabled(), "kernel request isolation", () => { + it("does not kill the kernel while another request is still pending", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-kernel-isolation-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(JSON.parse(notebook("import time\ntime.sleep(2)\nprint(1)")))) + const manager = makeKernelManager({ + pythonPath: "python", + helperPath: path.resolve("python", "ipynb_runner.py"), + workingDirectory: dir, + defaultTimeoutMs: 60_000 + }) + const request = (timeoutMs: number) => ({ + filePath: file, + mode: "all" as const, + timeoutMs, + save: false, + maxOutputChars: 2_000 + }) + const controller = new AbortController() + try { + const slow = Effect.runPromise(manager.execute(file, request(60_000))) + await new Promise((resolve) => setTimeout(resolve, 300)) + const cancelled = Effect.runPromiseExit( + manager.execute(file, request(60_000), undefined, { + signal: controller.signal + }) + ) + controller.abort() + const cancelledExit = await cancelled + expect(cancelledExit._tag).toBe("Failure") + const survivor = await slow + expect(survivor.success).toBe(true) + expect(manager.isRunning(file)).toBe(true) + } finally { + await Effect.runPromise(manager.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 180_000) +}) diff --git a/test/unit/kernel-symlink-shutdown.test.ts b/test/unit/kernel-symlink-shutdown.test.ts new file mode 100644 index 0000000..ed23366 --- /dev/null +++ b/test/unit/kernel-symlink-shutdown.test.ts @@ -0,0 +1,75 @@ +import { describe, expect, it } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { Effect } from "effect" +import { makeKernelManager } from "../../src/services/KernelManager.js" +import { makeWarningSink } from "../../src/utils/warnings.js" + +const notebook = { + cells: [{ cell_type: "code", execution_count: null, metadata: {}, outputs: [], source: "x = 1" }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 +} + +const writeScript = (dir: string, body: string): string => { + const file = path.join(dir, "helper.sh") + fs.writeFileSync(file, body, "utf8") + fs.chmodSync(file, 0o755) + return file +} + +const shellHelper = (dir: string): string => + writeScript( + dir, + `#!/bin/sh +IFS= read -r init +printf '{"ready": true, "pid": %s, "kernelPid": %s}\\n' "$$" "$$" +IFS= read -r req +id=$(printf '%s' "$req" | sed -n 's/.*"id"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p') +nonce=$(printf '%s' "$req" | sed -n 's/.*"nonce"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\\1/p') +printf '{"id": %s, "nonce": "%s", "success": true, "executedCells": [], "durationMs": 1, "outputs": []}\\n' "$id" "$nonce" +` + ) + +describe("kernel shutdown through a deleted symlink", () => { + it("stops the kernel that was started through the link", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-kernel-link-")) + const real = path.join(dir, "real.ipynb") + const link = path.join(dir, "link.ipynb") + fs.writeFileSync(real, JSON.stringify(notebook)) + fs.symlinkSync(real, link) + const helper = shellHelper(dir) + const sink = makeWarningSink() + const mgr = makeKernelManager({ + pythonPath: "/bin/sh", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 10_000, + warningSink: sink + }) + try { + await Effect.runPromise( + mgr.execute(link, { + filePath: link, + mode: "all", + timeoutMs: 10_000, + save: false, + maxOutputChars: 1_000 + }) + ) + const live = mgr.list() + expect(live).toHaveLength(1) + const pid = live[0]!.pid + fs.rmSync(link) + await Effect.runPromise(mgr.shutdown(link)) + expect(mgr.list()).toHaveLength(0) + expect(() => process.kill(pid, 0)).toThrow() + } finally { + await Effect.runPromise(mgr.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/kernel-warm-budget.test.ts b/test/unit/kernel-warm-budget.test.ts new file mode 100644 index 0000000..31f41bc --- /dev/null +++ b/test/unit/kernel-warm-budget.test.ts @@ -0,0 +1,63 @@ +import { describe, expect, it } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { Effect } from "effect" +import { makeKernelManager } from "../../src/services/KernelManager.js" + +const helperSource = ` +const out = (o) => process.stdout.write(JSON.stringify(o) + "\\n") +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) +let buf = "" +out({ ready: true, pid: process.pid, kernelPid: process.pid }) +process.stdin.setEncoding("utf8") +process.stdin.on("data", async (c) => { + buf += c + let i + while ((i = buf.indexOf("\\n")) >= 0) { + const line = buf.slice(0, i) + buf = buf.slice(i + 1) + if (!line.trim()) continue + const req = JSON.parse(line) + if (req.mode === "shutdown") process.exit(0) + const cells = req.mode === "all" ? 3 : 1 + for (let k = 0; k < cells; k += 1) await sleep(400) + out({ id: req.id, success: true, executedCells: [0], durationMs: 1, outputs: [] }) + } +}) +` + +describe("warm kernel request budget", () => { + it("counts the timeout per cell, not across the whole batch", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warm-budget-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, "{}") + const helper = path.join(dir, "helper.mjs") + fs.writeFileSync(helper, helperSource) + const manager = makeKernelManager({ + pythonPath: process.execPath, + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 60_000 + }) + const started = Date.now() + try { + const run = await Effect.runPromise( + manager.execute(file, { + filePath: file, + mode: "all", + timeoutMs: 700, + save: false, + maxOutputChars: 2_000 + }) + ) + const elapsed = Date.now() - started + expect(run.success).toBe(true) + expect(elapsed).toBeLessThan(5_000) + expect(manager.isRunning(file)).toBe(true) + } finally { + await Effect.runPromise(manager.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }, 60_000) +}) diff --git a/test/unit/lifecycle.test.ts b/test/unit/lifecycle.test.ts new file mode 100644 index 0000000..008684b --- /dev/null +++ b/test/unit/lifecycle.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import { + buildServices, + disposeSharedKernelManager +} from "../../src/services/index.js" +import type { ToolContext } from "../../src/tool.js" + +const base = { + sessionID: "test", + messageID: "test", + agent: "test", + directory: process.cwd(), + worktree: process.cwd(), + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} +} + +const contextFor = (scope: object): ToolContext => + ({ ...base, pluginScope: scope }) as unknown as ToolContext + +describe("kernel manager lifecycle", () => { + it("disposes the managers of a scope and hands out fresh ones afterwards", async () => { + const scopeA = {} + const scopeB = {} + const ctxA = contextFor(scopeA) + const ctxB = contextFor(scopeB) + const managerA = buildServices(ctxA).kernel + const managerB = buildServices(ctxB).kernel + expect(buildServices(ctxA).kernel).toBe(managerA) + expect(managerB).not.toBe(managerA) + + let disposedA = 0 + ;(managerA as unknown as { disposeAll: () => Effect.Effect }).disposeAll = + () => { + disposedA += 1 + return Effect.void + } + + await disposeSharedKernelManager(scopeA) + expect(disposedA).toBe(1) + const freshA = buildServices(ctxA).kernel + expect(freshA).not.toBe(managerA) + expect(buildServices(ctxB).kernel).toBe(managerB) + + await disposeSharedKernelManager() + expect(buildServices(ctxB).kernel).not.toBe(managerB) + }) + + it("disposing an unknown scope is a no-op", async () => { + const manager = buildServices(contextFor({})).kernel + await disposeSharedKernelManager({}) + expect(buildServices(contextFor({})).kernel).not.toBe(manager) + }) +}) diff --git a/test/unit/lsp-position-scaling.test.ts b/test/unit/lsp-position-scaling.test.ts new file mode 100644 index 0000000..81d8a4c --- /dev/null +++ b/test/unit/lsp-position-scaling.test.ts @@ -0,0 +1,59 @@ +import { describe, expect, it } from "bun:test" +import { + buildNotebookVirtualDocument, + toCellPosition, + toVirtualPosition, + type NotebookLike +} from "../../src/lsp.js" + +const CELLS = 40_000 +const LINES_PER_CELL = 2 + +const buildDocument = () => { + const cells = Array.from({ length: CELLS }, () => ({ + cell_type: "code", + source: "x = 1\ny = 2" + })) + const notebook = { + metadata: { language_info: { name: "python" } }, + cells + } as NotebookLike + return buildNotebookVirtualDocument(notebook) +} + +describe("virtual document cell spans", () => { + it("are sorted by startLine and contiguous", () => { + const document = buildDocument() + expect(document.cells.length).toBe(CELLS) + let expectedStart = 0 + for (const cell of document.cells) { + expect(cell.startLine).toBe(expectedStart) + expect(cell.endLine).toBe(expectedStart + LINES_PER_CELL) + expectedStart = cell.endLine + } + }) +}) + +describe("position mapping scale", () => { + it("maps every line of a large notebook within a linear budget", () => { + const document = buildDocument() + const started = Date.now() + for (let line = 0; line < CELLS * LINES_PER_CELL; line += 1) { + const mapped = toCellPosition(document, line, 0) + if (mapped === undefined) throw new Error(`unmapped line ${line}`) + if (mapped.cellIndex !== Math.floor(line / LINES_PER_CELL)) { + throw new Error(`wrong cell for line ${line}`) + } + } + expect(toCellPosition(document, CELLS * LINES_PER_CELL, 0)).toBeUndefined() + for (let cellIndex = 0; cellIndex < CELLS; cellIndex += 1) { + const virtual = toVirtualPosition(document, cellIndex, 1, 0) + if (virtual === undefined) throw new Error(`unmapped cell ${cellIndex}`) + if (virtual.line !== cellIndex * LINES_PER_CELL + 1) { + throw new Error(`wrong virtual line for cell ${cellIndex}`) + } + } + expect(toVirtualPosition(document, CELLS, 0, 0)).toBeUndefined() + expect(Date.now() - started).toBeLessThan(500) + }) +}) diff --git a/test/unit/lsp-tool.test.ts b/test/unit/lsp-tool.test.ts index ba07401..7e31adf 100644 --- a/test/unit/lsp-tool.test.ts +++ b/test/unit/lsp-tool.test.ts @@ -4,6 +4,7 @@ import * as os from "node:os" import * as path from "node:path" import { ipynbLspTool } from "../../src/tools/lsp.js" import type { ToolContext } from "../../src/tool.js" +import { makeWarningSink, type WarningSink } from "../../src/utils/warnings.js" type ObjectToolResult = { output: string; metadata?: Record } const runTool = async ( @@ -34,7 +35,7 @@ const makeNotebook = (language = "python"): string => ] }) -const makeContext = (dir: string): ToolContext => ({ +const makeContext = (dir: string, warningSink?: WarningSink): ToolContext => ({ sessionID: "ses_1", messageID: "msg_1", agent: "build", @@ -42,7 +43,8 @@ const makeContext = (dir: string): ToolContext => ({ worktree: dir, abort: new AbortController().signal, metadata: () => {}, - ask: async () => {} + ask: async () => {}, + ...(warningSink === undefined ? {} : { warningSink }) }) const fakePyright = (dir: string, body: string): string => { @@ -94,17 +96,19 @@ describe("ipynb_lsp tool", () => { } }) - it("reports missing pyright", async () => { + it("reports missing pyright and records the configured path that failed", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-lsp-missing-")) const file = path.join(dir, "notebook.ipynb") fs.writeFileSync(file, makeNotebook()) - process.env[ENV] = JSON.stringify({ - pyrightPath: path.join(dir, "does-not-exist") - }) + const configured = path.join(dir, "does-not-exist") + process.env[ENV] = JSON.stringify({ pyrightPath: configured }) + const sink = makeWarningSink() try { - const result = await runTool(file, makeContext(dir)) + const result = await runTool(file, makeContext(dir, sink)) expect(result.output).toContain("pyright was not found") expect(result.metadata?.skipped).toBe("pyright-not-found") + const warnings = sink.drain() + expect(warnings.some((warning) => (warning.detail ?? "").includes(configured))).toBe(true) } finally { fs.rmSync(dir, { recursive: true, force: true }) } @@ -293,6 +297,7 @@ describe("ipynb_lsp tool", () => { }) it("propagates a fallback-temp permission denial instead of returning normal content", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return if (process.platform === "win32") return const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-lsp-fallback-denial-")) const file = path.join(dir, "notebook.ipynb") diff --git a/test/unit/markdown-safe.test.ts b/test/unit/markdown-safe.test.ts index e5f2372..115cdb3 100644 --- a/test/unit/markdown-safe.test.ts +++ b/test/unit/markdown-safe.test.ts @@ -24,6 +24,15 @@ describe("sanitizeTerminal performance", () => { expect(Date.now() - started).toBeLessThan(2_000) expect(out).not.toContain("\u001b") }) + + it("strips a multi-megabyte unterminated OSC run in linear time", () => { + const text = ("\u001b]" + "a".repeat(100)).repeat(40_000) + const started = Date.now() + const out = sanitizeTerminal(text) + const elapsed = Date.now() - started + expect(out).not.toContain("\u001b") + expect(elapsed).toBeLessThan(300) + }) }) describe("sanitizeInline", () => { @@ -87,6 +96,17 @@ describe("truncateMarkdown", () => { ) expect(invalid.endsWith("... (truncated)")).toBe(true) }) + + it("squashes a pathological fence run and strips the cut's trailing newline exactly", () => { + const text = "`".repeat(40) + "\n" + "z".repeat(80) + const out = truncateMarkdown(text, 114, "TRUNCATED") + expect(out).toBe("```\n```\nTRUNCATED") + }) + + it("returns the normalized text unchanged when it fits", () => { + expect(truncateMarkdown("a\rb", 10, "")).toBe("a\nb") + expect(truncateMarkdown("a\r\nb", 10, "")).toBe("a\nb") + }) }) describe("formatOutputs label safety", () => { @@ -155,3 +175,23 @@ describe("formatOutputs fence balance", () => { expect(fenceCount(out) % 2).toBe(0) }) }) + +describe("truncateMarkdown never emits a lone surrogate", () => { + it("keeps every budget a well-formed string", () => { + const emoji = "\u{1F600}".repeat(50) + const offenders: number[] = [] + for (let budget = 1; budget <= 140; budget += 1) { + const result = truncateMarkdown(emoji, budget, "") + if ((result as { isWellFormed?: () => boolean }).isWellFormed?.() === false) { + offenders.push(budget) + } + } + expect(offenders).toEqual([]) + }) + + it("also stays well-formed when a hint is appended", () => { + const astral = "\u{1D11E}".repeat(40) + const result = truncateMarkdown(astral, 65, "... (truncated)") + expect((result as { isWellFormed?: () => boolean }).isWellFormed?.()).toBe(true) + }) +}) diff --git a/test/unit/notebook-defaults-purity.test.ts b/test/unit/notebook-defaults-purity.test.ts new file mode 100644 index 0000000..5d7cfa4 --- /dev/null +++ b/test/unit/notebook-defaults-purity.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "bun:test" +import { applyNotebookDefaults } from "../../src/domain/notebook.js" + +const deepFreeze = (value: unknown): void => { + if (value === null || typeof value !== "object") return + Object.freeze(value) + for (const key of Object.keys(value as Record)) { + deepFreeze((value as Record)[key]) + } +} + +describe("applyNotebookDefaults purity", () => { + it("never mutates the parsed notebook it is given", () => { + const raw = { + cells: [ + { cell_type: "code", execution_count: null, metadata: {}, source: ["a"] }, + { cell_type: "code", execution_count: 1, metadata: {}, outputs: [], source: ["b"] }, + { cell_type: "markdown", metadata: {}, source: ["c"] } + ], + nbformat: 4, + nbformat_minor: 5 + } + deepFreeze(raw) + const out = applyNotebookDefaults(raw) + expect(out.metadata).toEqual({}) + expect( + Object.prototype.hasOwnProperty.call( + (out.cells[0] as Record), + "outputs" + ) + ).toBe(true) + expect( + Object.prototype.hasOwnProperty.call( + (raw.cells[0] as Record), + "outputs" + ) + ).toBe(false) + expect(Object.keys(raw)).toEqual(["cells", "nbformat", "nbformat_minor"]) + }) + + it("keeps object identity for parts that need no default", () => { + const metadata = { a: 1 } + const untouchedCell = { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: ["b"] + } + const raw = { + cells: [untouchedCell, { cell_type: "markdown", metadata: {}, source: ["c"] }], + metadata, + nbformat: 4, + nbformat_minor: 5 + } + const out = applyNotebookDefaults(raw) + expect(out.metadata).toBe(metadata) + expect(out.cells[0] as unknown).toBe(untouchedCell as unknown) + expect(out.cells[1] as unknown).toBe(raw.cells[1] as unknown) + }) + + it("only clones the cells that actually receive a default", () => { + const raw = { + cells: [ + { cell_type: "code", execution_count: null, metadata: {}, source: ["a"] }, + { cell_type: "code", execution_count: null, metadata: {}, source: ["b"] } + ], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + } + const out = applyNotebookDefaults(raw) + expect(out.cells[0] as unknown).not.toBe(raw.cells[0] as unknown) + expect(out.cells[1] as unknown).not.toBe(raw.cells[1] as unknown) + expect(out.cells[0] as unknown).not.toBe(out.cells[1] as unknown) + }) + + it("applies defaults to a prototype-polluted cell without touching its sibling", () => { + const raw = JSON.parse( + `{"cells":[{"__proto__":{"p":"yes"},"cell_type":"code","execution_count":null,"metadata":{}},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[]}],"nbformat":4,"nbformat_minor":5}` + ) + const sibling = raw.cells[1] + const out = applyNotebookDefaults(raw) + expect(Object.keys(out.cells[0] as Record)).toContain("outputs") + expect(out.cells[1] as unknown).toBe(sibling as unknown) + }) +}) diff --git a/test/unit/notebook-diagnostics.test.ts b/test/unit/notebook-diagnostics.test.ts index b853d17..2dc10cc 100644 --- a/test/unit/notebook-diagnostics.test.ts +++ b/test/unit/notebook-diagnostics.test.ts @@ -128,6 +128,7 @@ describe("notebook diagnostics", () => { it("reports temp-unwritable when the fallback temp directory is also unwritable", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return if (process.platform === "win32") return const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-diag-ro-")) const fallback = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-diag-ro-tmp-")) @@ -499,6 +500,7 @@ sys.stdout.buffer.flush() }) it("places diagnostics next to the real notebook for symlink aliases", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return if (process.platform === "win32") return const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-diag-alias-")) const aliasDir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-diag-alias-link-")) @@ -507,7 +509,9 @@ sys.stdout.buffer.flush() fs.writeFileSync(real, "{}") fs.symlinkSync(real, alias) try { - expect(path.dirname(diagnosticTempPath(alias))).toBe(dir) + // The temp file lands next to the real notebook, which is the resolved + // directory; on macOS the lexical temp dir spells it through a symlink. + expect(path.dirname(diagnosticTempPath(alias))).toBe(fs.realpathSync(dir)) } finally { fs.rmSync(dir, { recursive: true, force: true }) fs.rmSync(aliasDir, { recursive: true, force: true }) @@ -759,3 +763,62 @@ sys.stdout.buffer.flush() }) }) + +describe("pyright file-level errors", () => { + it("keeps the batch when a diagnostic has no range", async () => { + if (process.platform === "win32") return + // The fake pyright is a python script; skip where no interpreter is usable. + const pythonUsable = (() => { + try { + return Bun.spawnSync(["python", "-c", "print(1)"], { + stdout: "pipe", + stderr: "pipe" + }).exitCode === 0 + } catch { + return false + } + })() + if (!pythonUsable) return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-diag-norange-")) + const file = path.join(dir, "notebook.ipynb") + const script = path.join(dir, "norange-pyright") + // A real pyright exits 1 when it reports errors, and omits `range` for a + // file-level report such as "Code is too complex to analyze". + fs.writeFileSync( + script, + `#!/bin/sh +exec python -c 'import json,sys +target = sys.argv[2] +print(json.dumps({ + "version": "1.1.0", + "generalDiagnostics": [ + {"file": target, "severity": "error", "message": "Code is too complex to analyze"}, + {"file": target, "severity": "error", "message": "real problem", + "range": {"start": {"line": 0, "character": 0}, "end": {"line": 0, "character": 4}}} + ], + "summary": {"filesAnalyzed": 1, "errorCount": 2, "warningCount": 0} +}))' "$@" +exit 1 +`, + "utf8" + ) + fs.chmodSync(script, 0o755) + const document = buildNotebookVirtualDocument(notebook, { filePath: file }) + try { + const result = await diagnoseNotebook({ + filePath: file, + document, + pyrightPath: script + }) + expect(result.skipped).toBeUndefined() + const messages = result.diagnostics.map((diagnostic) => diagnostic.message) + expect(messages).toContain("Code is too complex to analyze") + expect(messages).toContain("real problem") + expect( + result.diagnostics.some((diagnostic) => diagnostic.fileLevel === true) + ).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/notebook-file-atomic.test.ts b/test/unit/notebook-file-atomic.test.ts index 192aa63..49eba19 100644 --- a/test/unit/notebook-file-atomic.test.ts +++ b/test/unit/notebook-file-atomic.test.ts @@ -5,7 +5,7 @@ import * as os from "node:os" import * as path from "node:path" import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" import { NotebookSchema, type NotebookRaw } from "../../src/domain/notebook.js" -import { NotebookValidationError, NotebookWriteError } from "../../src/domain/errors.js" +import { NotebookValidationError } from "../../src/domain/errors.js" const makeMinimalNotebook = (label: string): NotebookRaw => ({ nbformat: 4, @@ -36,6 +36,7 @@ const runOrThrow = async ( describe("NotebookFileService.writeAtomic", () => { it("writes valid JSON that re-parses and equals the input", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return const fileSvc = makeNotebookFileService() const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-")) const file = path.join(dir, "out.ipynb") @@ -57,6 +58,7 @@ describe("NotebookFileService.writeAtomic", () => { }) it("creates parent directories if they do not exist", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return const fileSvc = makeNotebookFileService() const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-")) const nested = path.join(dir, "a", "b", "c") @@ -119,7 +121,7 @@ describe("NotebookFileService.writeAtomic", () => { } }) - it("cleans up the .tmp file when the rename fails (dest is a directory)", async () => { + it("refuses a directory target without leaving a .tmp file", async () => { const fileSvc = makeNotebookFileService() const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-")) const file = path.join(dir, "out.ipynb") @@ -129,7 +131,7 @@ describe("NotebookFileService.writeAtomic", () => { const result = await Effect.runPromise( fileSvc.writeAtomic(file, notebook).pipe(Effect.flip) ) - expect(result).toBeInstanceOf(NotebookWriteError) + expect(result).toBeInstanceOf(NotebookValidationError) const entries = fs.readdirSync(dir) const tmpFiles = entries.filter((e) => e.endsWith(".tmp")) expect(tmpFiles.length).toBe(0) diff --git a/test/unit/notebook-layout.test.ts b/test/unit/notebook-layout.test.ts new file mode 100644 index 0000000..688c891 --- /dev/null +++ b/test/unit/notebook-layout.test.ts @@ -0,0 +1,1176 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { + makeCleanImpl, + makeEditImpl, + makeExecutionImpl, + makeNotebookFileService, + makeOutputImpl, + makePathService, + makePermissionService +} from "../../src/services/index.js" +import { splitSourceLines } from "../../src/domain/notebook.js" +import { detectNotebookFormat, stringifyNotebook } from "../../src/utils/json.js" +import type { KernelManagerShape } from "../../src/services/KernelManager.js" +import type { PythonServiceShape } from "../../src/services/PythonService.js" +import type { ToolContext } from "../../src/tool.js" + +const FIXTURES = path.resolve(__dirname, "..", "fixtures") + +const makeFakeContext = (directory: string, worktree: string): ToolContext => + ({ + sessionID: "test", + messageID: "test", + agent: "test", + directory, + worktree, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + }) as unknown as ToolContext + +const runOrThrow = async ( + effect: Effect.Effect +): Promise => Effect.runPromise(effect as Effect.Effect) + +const setup = (dir: string) => { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const fileSvc = makeNotebookFileService() + const permSvc = makePermissionService(makeFakeContext(dir, dir)) + return { + pathSvc, + fileSvc, + permSvc, + edit: makeEditImpl(pathSvc, fileSvc, permSvc) + } +} + +const withTempRepo = async (fn: (dir: string) => Promise): Promise => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-layout-")) + try { + await fn(dir) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + + +describe("layout-preserving writes", () => { + it("collapses an emptied array to [] without stray whitespace", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "clear.ipynb") + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hi" + ] + } + ], + "source": [ + "print(1)" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 4 +} +` + fs.writeFileSync(file, text) + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { cellIndex: 0, source: "print(2)", clearOutputs: "always" }) + ) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain('"outputs": [],') + expect(after).not.toContain('"outputs": [\n') + }) + }) + + it("does not reflow an untouched inline source array (repo fixture)", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "simple.ipynb") + fs.copyFileSync(path.join(FIXTURES, "simple.ipynb"), file) + const before = fs.readFileSync(file, "utf8") + expect(before).toContain('"source": ["## Section\\n", "\\n", "Some notes."]') + + const { edit } = setup(dir) + // Cell 1 is the code cell; cell 2 is the untouched inline-array markdown. + await runOrThrow( + edit.editCell(file, { cellIndex: 1, source: "x = 1", clearOutputs: "never" }) + ) + + const after = fs.readFileSync(file, "utf8") + expect(after).toContain('"source": ["## Section\\n", "\\n", "Some notes."]') + }) + }) + + it("does not reflow if the edited value already matches", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "simple.ipynb") + fs.copyFileSync(path.join(FIXTURES, "simple.ipynb"), file) + const before = fs.readFileSync(file, "utf8") + const source = (JSON.parse(before) as { cells: Array<{ source: string | string[] }> }) + .cells[1]!.source + const { edit } = setup(dir) + const result = await runOrThrow( + edit.editCell(file, { + cellIndex: 1, + source: Array.isArray(source) ? source.join("") : source, + clearOutputs: "never" + }) + ) + expect(result.changed).toBe(false) + expect(fs.readFileSync(file, "utf8")).toBe(before) + }) + }) + + it("preserves indentation wider than JSON.stringify's 10-space clamp", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "twelve.ipynb") + const pad = (depth: number) => " ".repeat(depth * 12) + const emit = (value: unknown, depth = 0): string => { + if (value === null) return "null" + if (typeof value === "string") return JSON.stringify(value) + if (typeof value !== "object") return String(value) + if (Array.isArray(value)) { + if (value.length === 0) return "[]" + return `[\n${value + .map((item) => pad(depth + 1) + emit(item, depth + 1)) + .join(",\n")}\n${pad(depth)}]` + } + const record = value as Record + const keys = Object.keys(record) + if (keys.length === 0) return "{}" + return `{\n${keys + .map( + (key) => + `${pad(depth + 1)}${JSON.stringify(key)}: ${emit(record[key], depth + 1)}` + ) + .join(",\n")}\n${pad(depth)}}` + } + const notebook = { + cells: [ + { cell_type: "markdown", metadata: {}, source: ["# A"] }, + { cell_type: "markdown", metadata: {}, source: ["# B"] } + ], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + } + const twelve = `${emit(notebook)}\n` + fs.writeFileSync(file, twelve) + expect(twelve.split("\n")[1]).toBe(`${" ".repeat(12)}"cells": [`) + + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { cellIndex: 0, source: "# Edited", clearOutputs: "never" }) + ) + const after = fs.readFileSync(file, "utf8") + expect(after.split("\n")[1]).toBe(`${" ".repeat(12)}"cells": [`) + expect(after).toContain(`${" ".repeat(12 * 3)}"# B"`) + }) + }) + + it("keeps \\uXXXX escapes in untouched cells", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "escaped.ipynb") + const text = `{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# A" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print('hello \\u2014 dash')" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 4 +} +` + fs.writeFileSync(file, text) + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { cellIndex: 0, source: "# Edited", clearOutputs: "never" }) + ) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain("\\u2014") + expect(after).not.toContain("\u2014") + }) + }) + + it("keeps number literals in untouched metadata", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "numbers.ipynb") + const text = `{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# A" + ] + } + ], + "metadata": { + "big": 12345678901234567890, + "float": 1.0, + "exp": 1e20 + }, + "nbformat": 4, + "nbformat_minor": 4 +} +` + fs.writeFileSync(file, text) + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { cellIndex: 0, source: "# Edited", clearOutputs: "never" }) + ) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain("12345678901234567890") + expect(after).toContain("1.0") + expect(after).toContain("1e20") + }) + }) + + it("keeps single-line separators in untouched parts", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "oneline.ipynb") + const text = + '{"cells": [{"cell_type": "markdown", "metadata": {}, "source": "# A"}], "metadata": {}, "nbformat": 4, "nbformat_minor": 4}\n' + fs.writeFileSync(file, text) + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { cellIndex: 0, source: "# Edited", clearOutputs: "never" }) + ) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain('"cell_type": "markdown", "metadata": {}, "source": "# Edited"') + expect(Object.keys(JSON.parse(after))).toEqual([ + "cells", + "metadata", + "nbformat", + "nbformat_minor" + ]) + }) + }) + + it("only changes the edited cell's bytes in a 13-cell notebook", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "many.ipynb") + const cells = Array.from({ length: 13 }, (_, i) => ({ + cell_type: i % 2 === 0 ? "markdown" : "code", + ...(i % 2 === 0 + ? {} + : { execution_count: null, outputs: [] }), + metadata: { tag: `cell-${i}` }, + source: [`line ${i}\n`, `more ${i}`] + })) + const text = `${JSON.stringify({ cells, metadata: {}, nbformat: 4, nbformat_minor: 5 }, null, 1)}\n` + fs.writeFileSync(file, text) + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { cellIndex: 3, source: "changed", clearOutputs: "never" }) + ) + const after = fs.readFileSync(file, "utf8") + const oldBlock = [ + ' "source": [', + ' "line 3\\n",', + ' "more 3"', + ' ]' + ].join("\n") + expect(text).toContain(oldBlock) + // A line-array notebook keeps the array shape on the edited cell. + const expected = text.replace( + oldBlock, + [' "source": [', ' "changed"', " ]"].join("\n") + ) + expect(after).toBe(expected) + expect(after).toContain('"line 12\\n"') + expect(after).toContain('"source": [') + }) + }) +}) + +describe("nbformat output shape on ipynb_run save", () => { + const pythonSvc = { + probe: () => + Effect.succeed({ + pythonPath: "/usr/bin/python3", + version: "3", + executable: "python3", + from: "options" as const + }), + findHelper: () => Effect.succeed("/tmp/ipynb_runner.py"), + checkDependencies: () => Effect.succeed([]), + candidates: () => Effect.succeed([]), + checkImport: () => Effect.succeed({ name: "x", available: true, detail: "ok" }), + doctor: () => Effect.succeed({} as never) + } as unknown as PythonServiceShape + + it("persists nbformat's line arrays for stream text and text/* data", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "outputs.ipynb") + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(1)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print(2)" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 4 +} +` + fs.writeFileSync(file, text) + const { pathSvc, fileSvc, permSvc } = setup(dir) + // What nbformat.read() hands back: rejoin_lines turned arrays into strings. + const rawOutputs = [ + { name: "stdout", output_type: "stream", text: "line1\nline2\n" }, + { + data: { "text/html": "1", "text/plain": "a\nb" }, + execution_count: 1, + metadata: {}, + output_type: "execute_result" + } + ] + const kernel = { + execute: () => + Effect.succeed({ + success: true, + executedCells: [1], + durationMs: 1, + outputs: [ + { + cellIndex: 1, + status: "ok" as const, + stdout: "line1\nline2\n", + executionCount: 1, + rawOutputs + } + ] + }) + } as unknown as KernelManagerShape + const exec = makeExecutionImpl(pathSvc, fileSvc, permSvc, pythonSvc, { + kernelManager: kernel, + warmKernel: true, + defaultTimeoutMs: 30_000 + }) + + const result = await runOrThrow( + exec.execute(file, { + mode: "cell", + cellIndex: 1, + start: undefined, + end: undefined, + kernel: undefined, + timeoutMs: 30_000, + save: true, + workingDirectory: undefined, + maxOutputChars: 4_000 + }) + ) + expect(result.saved).toBe(true) + + const stored = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ outputs: Array> }> + } + const outputs = stored.cells[1]!.outputs + expect(outputs[0]).toEqual({ + name: "stdout", + output_type: "stream", + text: ["line1\n", "line2\n"] + }) + expect((outputs[1]!.data as Record)["text/html"]).toEqual([ + "1" + ]) + expect((outputs[1]!.data as Record)["text/plain"]).toEqual([ + "a\n", + "b" + ]) + // The unexecuted cell must stay byte-identical. + expect(fs.readFileSync(file, "utf8")).toContain(`"source": [ + "print(1)" + ]`) + }) + }) + + it("keeps stored text arrays in a hybrid notebook with string sources", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "hybrid.ipynb") + // String `source`, but the outputs were stored as line arrays. + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "old\\n" + ] + } + ], + "source": "print(1)" + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 4 +} +` + fs.writeFileSync(file, text) + const { pathSvc, fileSvc, permSvc } = setup(dir) + const kernel = { + execute: () => + Effect.succeed({ + success: true, + executedCells: [0], + durationMs: 1, + outputs: [ + { + cellIndex: 0, + status: "ok" as const, + stdout: "new\nline\n", + executionCount: 1, + rawOutputs: [ + { name: "stdout", output_type: "stream", text: "new\nline\n" } + ] + } + ] + }) + } as unknown as KernelManagerShape + const exec = makeExecutionImpl(pathSvc, fileSvc, permSvc, pythonSvc, { + kernelManager: kernel, + warmKernel: true, + defaultTimeoutMs: 30_000 + }) + await runOrThrow( + exec.execute(file, { + mode: "cell", + cellIndex: 0, + start: undefined, + end: undefined, + kernel: undefined, + timeoutMs: 30_000, + save: true, + workingDirectory: undefined, + maxOutputChars: 4_000 + }) + ) + const stored = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[]; outputs: Array> }> + } + expect(stored.cells[0]?.outputs[0]?.text).toEqual(["new\n", "line\n"]) + expect(typeof stored.cells[0]?.source).toBe("string") + }) + }) +}) + +describe("defaults keep nbformat key order", () => { + it("inserts a defaulted outputs key in sorted position", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "missing.ipynb") + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "source": [ + "x = 1" + ] + } + ], + "nbformat": 4, + "nbformat_minor": 5 +} +` + fs.writeFileSync(file, text) + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { cellIndex: 0, source: "x = 2", clearOutputs: "never" }) + ) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array> + } + expect(Object.keys(after)).toEqual([ + "cells", + "metadata", + "nbformat", + "nbformat_minor" + ]) + expect(Object.keys(after.cells[0]!)).toEqual([ + "cell_type", + "execution_count", + "metadata", + "outputs", + "source" + ]) + }) + }) +}) + +describe("splitSourceLines matches Python splitlines(keepends=True)", () => { + it("splits on every boundary Python honors", () => { + expect(splitSourceLines("a\nb")).toEqual(["a\n", "b"]) + expect(splitSourceLines("a\rb")).toEqual(["a\r", "b"]) + expect(splitSourceLines("a\r\nb")).toEqual(["a\r\n", "b"]) + expect(splitSourceLines("a\vb")).toEqual(["a\v", "b"]) + expect(splitSourceLines("a\fb")).toEqual(["a\f", "b"]) + expect(splitSourceLines("a\x1cb")).toEqual(["a\x1c", "b"]) + expect(splitSourceLines("a\x1db")).toEqual(["a\x1d", "b"]) + expect(splitSourceLines("a\x1eb")).toEqual(["a\x1e", "b"]) + expect(splitSourceLines("a\x85b")).toEqual(["a\x85", "b"]) + expect(splitSourceLines("a\u2028b")).toEqual(["a\u2028", "b"]) + expect(splitSourceLines("a\u2029b")).toEqual(["a\u2029", "b"]) + expect(splitSourceLines("")).toEqual([]) + expect(splitSourceLines("\n\n")).toEqual(["\n", "\n"]) + expect(splitSourceLines("a\r\nb\r\n")).toEqual(["a\r\n", "b\r\n"]) + expect(splitSourceLines("abc")).toEqual(["abc"]) + expect(splitSourceLines("a\nb\r\nc\rd")).toEqual(["a\n", "b\r\n", "c\r", "d"]) + }) +}) + +describe("untouched bytes across every writer", () => { + const literalNotebook = `{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": ["# A", "# B"] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# C" + ] + } + ], + "metadata": { + "big": 12345678901234567890, + "float": 1.0, + "inline": ["x"] + }, + "nbformat": 4, + "nbformat_minor": 4 +} +` + + const withFile = async ( + text: string, + action: (dir: string, file: string) => Promise + ): Promise<{ before: string; after: string }> => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-writer-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, text) + try { + await action(dir, file) + return { before: text, after: fs.readFileSync(file, "utf8") } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + } + + it("ipynb_cell_delete(0) keeps literals, inline arrays and untouched cells", async () => { + const { before, after } = await withFile(literalNotebook, async (dir, file) => { + await runOrThrow(setup(dir).edit.deleteCell(file, 0)) + }) + expect(after).toContain("12345678901234567890") + expect(after).toContain("1.0") + expect(after).toContain('"inline": ["x"]') + expect(JSON.parse(after).cells.length).toBe(1) + expect(JSON.parse(after).cells[0].source).toEqual(["# C"]) + expect(before.length - after.length).toBeLessThan(120) + }) + + it("ipynb_cell_move keeps literals and inline arrays", async () => { + const { after } = await withFile(literalNotebook, async (dir, file) => { + await runOrThrow(setup(dir).edit.moveCell(file, 0, 1)) + }) + expect(after).toContain("12345678901234567890") + expect(after).toContain("1.0") + expect(after).toContain('"inline": ["x"]') + expect(Object.keys(JSON.parse(after))).toEqual([ + "cells", + "metadata", + "nbformat", + "nbformat_minor" + ]) + }) + + it("ipynb_outputs clear_all keeps literals and inline arrays", async () => { + const { after } = await withFile(literalNotebook, async (dir, file) => { + await runOrThrow( + makeOutputImpl( + makePathService({ directory: dir, worktree: dir, platform: process.platform }), + makeNotebookFileService(), + makePermissionService(makeFakeContext(dir, dir)) + ).clearAllOutputs(file) + ) + }) + expect(after).toContain("12345678901234567890") + expect(after).toContain("1.0") + expect(after).toContain('"inline": ["x"]') + }) + + it("clearOutputs: never preserves a committed execution_count", async () => { + const { after } = await withFile(literalNotebook, async (dir, file) => { + const stored = JSON.parse(literalNotebook) as { + cells: Array> + } + stored.cells[0] = { + cell_type: "code", + execution_count: 7, + metadata: {}, + outputs: [{ name: "stdout", output_type: "stream", text: ["hi\n"] }], + source: ["print(1)"] + } + fs.writeFileSync(file, `${JSON.stringify(stored, null, 1)}\n`) + await runOrThrow( + setup(dir).edit.editCell(file, { + cellIndex: 0, + source: "print(2)", + clearOutputs: "never" + }) + ) + }) + const cell = (JSON.parse(after) as { cells: Array> }).cells[0]! + expect(cell.execution_count).toBe(7) + expect((cell.outputs as unknown[]).length).toBe(1) + expect(cell.source).toEqual(["print(2)"]) + }) +}) + +describe("inserted cells mirror the notebook's source shape", () => { + it("inserts array source into a line-array notebook", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "arrays.ipynb") + fs.copyFileSync(path.join(FIXTURES, "simple.ipynb"), file) + const { edit } = setup(dir) + await runOrThrow(edit.insertCell(file, "code", "a = 1\nb = 2", 1)) + const stored = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[] }> + } + expect(stored.cells[1]?.source).toEqual(["a = 1\n", "b = 2"]) + }) + }) +}) + +describe("format detection and serialization round-trip", () => { + const notebook = { + cells: [ + { cell_type: "markdown", metadata: {}, source: ["# A"] }, + { cell_type: "code", execution_count: 1, metadata: {}, outputs: [], source: ["x"] } + ], + metadata: { big: "12345678901234567890" }, + nbformat: 4, + nbformat_minor: 4 + } + + const emit = (indent: string): string => { + const pad = (depth: number) => indent.repeat(depth) + const walk = (value: unknown, depth: number): string => { + if (value === null) return "null" + if (typeof value === "string") return JSON.stringify(value) + if (typeof value !== "object") return String(value) + if (Array.isArray(value)) { + if (value.length === 0) return "[]" + return `[\n${value + .map((item) => pad(depth + 1) + walk(item, depth + 1)) + .join(",\n")}\n${pad(depth)}]` + } + const record = value as Record + const keys = Object.keys(record) + if (keys.length === 0) return "{}" + return `{\n${keys + .map((key) => `${pad(depth + 1)}${JSON.stringify(key)}: ${walk(record[key], depth + 1)}`) + .join(",\n")}\n${pad(depth)}}` + } + return walk(notebook, 0) + } + + for (const indent of [" ", " ", " ", "\t", " ".repeat(12)]) { + for (const newline of ["\n", "\r\n"] as const) { + for (const trailingNewline of [true, false]) { + const label = `indent=${JSON.stringify(indent)} newline=${JSON.stringify(newline)} trailing=${trailingNewline}` + it(`round-trips ${label}`, () => { + const text = `${emit(indent).replace(/\n/g, newline)}${ + trailingNewline ? newline : "" + }` + const format = detectNotebookFormat(text) + expect(format.newline).toBe(newline) + expect(format.trailingNewline).toBe(trailingNewline) + expect(format.unit).toBe(indent) + const out = stringifyNotebook(notebook, format) + expect(out).toBe(text) + expect(out).not.toContain("\r\r\n") + }) + } + } + } + + it("emits LF for an LF format and CRLF for a CRLF format", () => { + const lf = stringifyNotebook(notebook, { ...detectNotebookFormat("{}\n"), newline: "\n" }) + expect(lf).not.toContain("\r") + const crlf = stringifyNotebook(notebook, { ...detectNotebookFormat("{}\n"), newline: "\r\n" }) + expect((crlf.match(/\r\n/g) ?? []).length).toBe((crlf.match(/\n/g) ?? []).length) + }) + + it("detects ASCII escapes", () => { + const escaped = `{\n "cells": [],\n "metadata": {},\n "nbformat": 4,\n "note": "caf\\u00e9"\n}\n` + expect(detectNotebookFormat(escaped).ensureAscii).toBe(true) + expect(detectNotebookFormat(`${escaped}`.replace("caf\\u00e9", "café")).ensureAscii).toBe(false) + }) + +}) + +describe("large notebooks stay linear", () => { + const build = (cells: number): string => { + const list = Array.from({ length: cells }, (_, i) => ({ + cell_type: "code", + execution_count: i, + metadata: {}, + outputs: [{ name: "stdout", output_type: "stream", text: [`line ${i}\n`] }], + source: [`print(${i})`] + })) + return `${JSON.stringify({ cells: list, metadata: {}, nbformat: 4, nbformat_minor: 4 }, null, 1)}\n` + } + + it("clears every output in 4000 cells without quadratic blowup", async () => { + const measure = async (cells: number): Promise => { + const text = build(cells) + const dir = fs.mkdtempSync(path.join(os.tmpdir(), `ipynb-linear-${cells}-`)) + const file = path.join(dir, "many.ipynb") + fs.writeFileSync(file, text) + try { + const { pathSvc, fileSvc, permSvc } = setup(dir) + const output = makeOutputImpl(pathSvc, fileSvc, permSvc) + const started = Date.now() + const result = await runOrThrow(output.clearAllOutputs(file)) + expect(result.clearedCells).toBe(cells) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ outputs: unknown[]; execution_count: unknown }> + } + expect(after.cells.every((cell) => cell.outputs.length === 0)).toBe(true) + expect(after.cells.every((cell) => cell.execution_count === null)).toBe(true) + return Date.now() - started + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + } + // A 4x larger notebook must not cost 4x more per cell (quadratic is ~8-11x). + await measure(500) + await measure(1000) + const small = await measure(1000) + const large = await measure(4000) + expect(large).toBeLessThan(Math.max(150, small * 5)) + }) +}) + +describe("external writers are never silently overwritten", () => { + it("rejects a write when the file changed during serialization", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "race.ipynb") + const cells = Array.from({ length: 4000 }, (_, i) => ({ + cell_type: "code", + execution_count: i, + metadata: {}, + outputs: [{ name: "stdout", output_type: "stream", text: [`l${i}\n`] }], + source: [`print(${i})`] + })) + const base = `${JSON.stringify({ cells, metadata: {}, nbformat: 4, nbformat_minor: 4 }, null, 1)}\n` + fs.writeFileSync(file, base) + const sentinel = base.replace('"print(0)"', '"EXTERNAL"') + const { edit } = setup(dir) + const timer = setTimeout(() => fs.writeFileSync(file, sentinel), 30) + try { + const exit = await Effect.runPromiseExit( + edit.editCell(file, { cellIndex: 5, source: "print('X')", clearOutputs: "never" }) + ) + const after = fs.readFileSync(file, "utf8") + if (exit._tag === "Failure") { + // Detected the external edit: its content is intact and ours is absent. + expect(after).toContain("EXTERNAL") + expect(after).not.toContain("print('X')") + } else { + // The external write landed after ours completed. + expect(after).not.toContain("EXTERNAL") + } + } finally { + clearTimeout(timer) + } + }) + }) +}) + +describe("key insertions and empty arrays stay spliceable", () => { + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + + it("inserts several new keys into an empty object", async () => { + const { patchJsonText } = await import("../../src/utils/json-patch.js") + for (const next of [{ a: 1 }, { a: 1, b: 2 }, { a: 1, b: 2, c: 3 }]) { + const text = `{\n "m": {}\n}\n` + const out = patchJsonText(text, { m: next }, { style }) + expect(out).toBeDefined() + expect(JSON.parse(out!)).toEqual({ m: next }) + expect(out).not.toContain('"a":1') + } + }) + + it("inserts a new key before and after existing keys", async () => { + const { patchJsonText } = await import("../../src/utils/json-patch.js") + const text = `{\n "m": {\n "x": 0\n }\n}\n` + const out = patchJsonText(text, { m: { a: 1, x: 0, z: 2 } }, { style }) + expect(out).toBeDefined() + expect(JSON.parse(out!)).toEqual({ m: { a: 1, x: 0, z: 2 } }) + expect(out).toContain('"a": 1') + expect(out).toContain('"z": 2') + }) + + it("expands a previously empty array into nbformat layout", async () => { + const { patchJsonText } = await import("../../src/utils/json-patch.js") + const text = `{\n "cells": [\n {\n "cell_type": "code",\n "outputs": [],\n "source": [\n "print(1)"\n ]\n }\n ],\n "nbformat": 4\n}\n` + const next = JSON.parse(text) as { + cells: Array<{ outputs: unknown[] }> + } + next.cells[0]!.outputs = [ + { name: "stdout", output_type: "stream", text: ["a\n"] } + ] + const out = patchJsonText(text, next, { style }) + expect(out).toBeDefined() + expect(JSON.parse(out!).cells[0].outputs).toEqual(next.cells[0]!.outputs) + expect(out).toContain('"outputs": [\n') + expect(out).not.toContain('"outputs": [{') + }) + + it("keeps an in-place metadata strip spliceable through ipynb_clean", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "widgets.ipynb") + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "jupyter": { + "outputs": {}, + "widgets": {} + }, + "tags": [ + "keep" + ] + }, + "outputs": [], + "source": [ + "x = 1" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + fs.writeFileSync(file, text) + const inline = `"source": ["x = 1"]` + const md = text.replace(`"source": [\n "x = 1"\n ]`, inline) + fs.writeFileSync(file, md) + const { pathSvc, fileSvc, permSvc } = setup(dir) + const clean = makeCleanImpl(pathSvc, fileSvc, permSvc) + await runOrThrow( + clean.clean(file, { + clearOutputs: false, + clearExecutionCount: false, + stripWidgetState: true, + stripLargeImages: false, + normalizeSource: false + }) + ) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain(inline) + const metadata = (JSON.parse(after) as { cells: Array<{ metadata: unknown }> }) + .cells[0]!.metadata as Record + expect(metadata["jupyter"]).toEqual({}) + expect(metadata["tags"]).toEqual(["keep"]) + }) + }) +}) + +describe("numeric literals survive reordering", () => { + const literal = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "cellId": 12345678901234567890, + "version": 1.0 + }, + "outputs": [], + "source": [ + "a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "b" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 4 +} +` + + it("ipynb_cell_move keeps 20-digit ids and 1.0 in the moved cell", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, literal) + const { edit } = setup(dir) + await runOrThrow(edit.moveCell(file, 0, 1)) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain("12345678901234567890") + expect(after).toContain('"version": 1.0') + expect(after).not.toContain("12345678901234567000") + }) + }) + + it("ipynb_cell_delete keeps literals in the surviving cell", async () => { + await withTempRepo(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, literal) + const { edit } = setup(dir) + await runOrThrow(edit.deleteCell(file, 1)) + const after = fs.readFileSync(file, "utf8") + expect(after).toContain("12345678901234567890") + expect(after).toContain('"version": 1.0') + }) + }) + + it("applyNotebookDefaults never turns __proto__ into a prototype write", async () => { + const { applyNotebookDefaults } = await import("../../src/domain/notebook.js") + const raw = JSON.parse( + `{"cells":[{"__proto__":{"polluted":"yes"},"cell_type":"code","execution_count":null,"metadata":{}}],"nbformat":4,"nbformat_minor":5}` + ) + const out = applyNotebookDefaults(raw) + const cell = out.cells[0] as Record + expect(Object.prototype.hasOwnProperty.call(cell, "__proto__")).toBe(true) + expect((cell as { polluted?: unknown }).polluted).toBeUndefined() + expect(Object.keys(cell)).toEqual([ + "__proto__", + "cell_type", + "execution_count", + "metadata", + "outputs" + ]) + }) +}) + +describe("format detection edge cases", () => { + it("does not conflate an empty object with an empty array", async () => { + const { jsonEqual } = await import("../../src/utils/json-patch.js") + expect(jsonEqual({}, [])).toBe(false) + expect(jsonEqual([], {})).toBe(false) + expect(jsonEqual([], [])).toBe(true) + expect(jsonEqual({}, {})).toBe(true) + expect(jsonEqual({ a: [] }, { a: {} })).toBe(false) + }) + + it("patches an empty array into an empty object", async () => { + const { patchJsonText } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ",", + keySeparator: ": ", + ensureAscii: false + } + const text = `{\n "cells": [\n {\n "metadata": [],\n "source": ["# a"]\n }\n ]\n}\n` + const next = JSON.parse(text) as { cells: Array<{ metadata: unknown }> } + next.cells[0]!.metadata = {} + const out = patchJsonText(text, next, { style }) + expect(out).toBeDefined() + expect((JSON.parse(out!) as { cells: Array<{ metadata: unknown }> }).cells[0]!.metadata).toEqual({}) + }) + + it("detects compact separators instead of injecting spaces", async () => { + const tight = `{"cells":[{"cell_type":"markdown","metadata":{},"source":["# a"]}],"metadata":{},"nbformat":4}\n` + const format = detectNotebookFormat(tight) + expect(format.itemSeparator).toBe(",") + expect(format.keySeparator).toBe(":") + const spaced = `{\n "cells": [\n {\n "cell_type": "markdown"\n }\n ]\n}\n` + expect(detectNotebookFormat(spaced).itemSeparator).toBe(",") + expect(detectNotebookFormat(spaced).keySeparator).toBe(": ") + }) + + it("sees non-ASCII escapes after ASCII control escapes", () => { + const ansi = `{\n "outputs": [\n {\n "text": "\\u001b[0;31mred\\u001b[0m caf\\u00e9"\n }\n ]\n}\n` + expect(detectNotebookFormat(ansi).ensureAscii).toBe(true) + }) +}) + +describe("ASCII escape detection", () => { + const detect = (text: string) => detectNotebookFormat(text).ensureAscii + + it("detects a real non-ASCII escape", () => { + expect(detect(`{\n "n": "caf\\u00e9"\n}\n`)).toBe(true) + expect(detect(`{\n "n": "\\u2014"\n}\n`)).toBe(true) + expect(detect(`{\n "n": "\\u4e2d"\n}\n`)).toBe(true) + expect(detect(`{\n "n": "\\ud83d"\n}\n`)).toBe(true) + }) + + it("ignores ASCII-only escapes", () => { + expect(detect(`{\n "n": "a\\u0000b"\n}\n`)).toBe(false) + expect(detect(`{\n "n": "a\\u001bb"\n}\n`)).toBe(false) + expect(detect(`{\n "n": "a\\u007fb"\n}\n`)).toBe(false) + }) + + it("ignores an escaped backslash before a u sequence", () => { + expect(detect(`{\n "n": "s = \\"\\\\u00e9\\""\n}\n`)).toBe(false) + }) + + it("finds a non-ASCII escape that follows an ASCII one", () => { + expect(detect(`{\n "n": "\\u001b[31m caf\\u00e9"\n}\n`)).toBe(true) + }) + + it("ignores plain unicode", () => { + expect(detect(`{\n "n": "café — 中文"\n}\n`)).toBe(false) + }) +}) + +describe("defaults respect the file's existing key order", () => { + const apply = async (raw: Record) => { + const { applyNotebookDefaults } = await import("../../src/domain/notebook.js") + return applyNotebookDefaults(raw) as Record + } + + it("inserts sorted when the object is already sorted", async () => { + const out = await apply({ + cells: [{ cell_type: "code", execution_count: null, metadata: {}, source: ["x"] }], + nbformat: 4, + nbformat_minor: 5 + }) + expect(Object.keys(out)).toEqual(["cells", "metadata", "nbformat", "nbformat_minor"]) + expect( + Object.keys((out.cells as Array>)[0]!) + ).toEqual([ + "cell_type", + "execution_count", + "metadata", + "outputs", + "source" + ]) + }) + + it("appends instead of reordering an unsorted object", async () => { + const out = await apply({ + cells: [ + { source: ["x"], metadata: {}, execution_count: null, cell_type: "code" } + ], + nbformat_minor: 5, + nbformat: 4 + }) + expect(Object.keys(out)).toEqual(["cells", "nbformat_minor", "nbformat", "metadata"]) + }) + + it("treats astral keys through UTF-16 order, which is unsorted in code points", async () => { + const out = await apply({ + "\u{FFFD}a": 1, + "\u{10000}b": 2, + cells: [] + }) + expect(Object.keys(out).pop()).toBe("metadata") + expect(out["\u{FFFD}a" as keyof typeof out]).toBe(1) + expect(out["\u{10000}b" as keyof typeof out]).toBe(2) + }) + + it("is idempotent: defaulting a defaulted notebook changes nothing", async () => { + const sorted = await apply({ + cells: [ + { cell_type: "code", execution_count: null, metadata: {}, source: ["x"] } + ], + nbformat: 4, + nbformat_minor: 5 + }) + expect(await apply(sorted)).toEqual(sorted) + const unsorted = await apply({ + cells: [ + { source: ["x"], metadata: {}, execution_count: null, cell_type: "code" } + ], + nbformat_minor: 5, + nbformat: 4 + }) + expect(await apply(unsorted)).toEqual(unsorted) + expect(JSON.stringify(await apply(sorted))).toBe(JSON.stringify(sorted)) + }) + + it("leaves an object that already has the key untouched", async () => { + const cell = { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [{ output_type: "stream" }], + source: ["x"] + } + const out = await apply({ cells: [cell], nbformat: 4, nbformat_minor: 5 }) + expect((out.cells as unknown as [Record])[0]!.outputs).toEqual([ + { output_type: "stream" } + ]) + }) +}) diff --git a/test/unit/notebook-splice-visibility.test.ts b/test/unit/notebook-splice-visibility.test.ts new file mode 100644 index 0000000..7237471 --- /dev/null +++ b/test/unit/notebook-splice-visibility.test.ts @@ -0,0 +1,292 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { + makeEditImpl, + makeNotebookFileService, + makePathService, + makePermissionService +} from "../../src/services/index.js" +import type { ToolContext } from "../../src/tool.js" +import { makeWarningSink } from "../../src/utils/warnings.js" + +const ctx = (d: string) => ({ + sessionID: "t", + messageID: "t", + agent: "t", + directory: d, + worktree: d, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} +}) as unknown as ToolContext + +const run = async (e: Effect.Effect) => + Effect.runPromise(e as Effect.Effect) + +const setup = (dir: string) => { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const fileSvc = makeNotebookFileService() + return makeEditImpl(pathSvc, fileSvc, makePermissionService(ctx(dir))) +} + +const notebook = `{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": "# A" + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + +describe("write mode is observable", () => { + it("reports patched when only the edited value changed", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "splice-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + try { + const result = await run( + setup(dir).editCell(file, { cellIndex: 0, source: "# B", clearOutputs: "never" }) + ) + expect(result.writeMode).toBe("patched") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports no write mode when the edit changes nothing", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "splice-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const before = fs.readFileSync(file, "utf8") + try { + const result = await run( + setup(dir).editCell(file, { cellIndex: 0, source: "# A", clearOutputs: "never" }) + ) + expect(result.changed).toBe(false) + expect(result.writeMode).toBeUndefined() + expect(fs.readFileSync(file, "utf8")).toBe(before) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports fallback with a reason when the splice cannot be trusted", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "splice-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const sink = makeWarningSink() + try { + const fileSvc = makeNotebookFileService({ warningSink: sink }) + const document = JSON.parse(notebook) as { + cells: Array> + metadata: Record + } + const next = { + ...document, + metadata: { ...document.metadata, ans: NaN } + } + const read = await Effect.runPromise(fileSvc.readWithText(file)) + const outcome = await Effect.runPromise( + fileSvc.writeAtomic(file, next as never, { + format: read.format, + previousText: read.text + }) + ) + expect(outcome.mode).toBe("fallback") + expect(outcome.reason).toBe("verification-failed") + expect(sink.drain().some((warning: { source: string }) => warning.source === "json-patch")).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("propagates the write outcome from the service instead of assuming a patch", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "splice-outcome-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + try { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const real = makeNotebookFileService() + const fileSvc = { + ...real, + writeAtomic: (() => Effect.succeed({ mode: "fallback" as const, reason: "not-representable" as const })) as typeof real.writeAtomic + } + const edit = makeEditImpl(pathSvc, fileSvc, makePermissionService(ctx(dir))) + const result = await run( + edit.editCell(file, { cellIndex: 0, source: "# B", clearOutputs: "never" }) + ) + expect(result.writeMode).toBe("fallback") + expect(result.writeModeReason).toBe("not-representable") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("surfaces a fallback reason from the patcher", async () => { + const { patchJsonTextDetailed } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ",", + keySeparator: ": ", + ensureAscii: false + } + const broken = `{ not json ` + const result = patchJsonTextDetailed(broken, { a: 1 }, { style }) + expect(result.text).toBeUndefined() + expect(result.reason).toBe("parse-failed") + }) + + it("patches an inline object whose every key is replaced", async () => { + const { patchJsonTextDetailed } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ",", + keySeparator: ": ", + ensureAscii: false + } + const result = patchJsonTextDetailed('{"x": 1}', { y: 2 }, { style }) + expect(result.reason).toBeUndefined() + expect(result.text).toBe('{"y": 2}') + }) + + it("patches a multiline object whose every key is replaced", async () => { + const { patchJsonTextDetailed } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ",", + keySeparator: ": ", + ensureAscii: false + } + const result = patchJsonTextDetailed('{\n "x": 1\n}', { y: 2 }, { style }) + expect(result.reason).toBeUndefined() + expect(result.text).toBe('{\n "y": 2\n}') + }) + + it("keeps sibling bytes when a nested object replaces every key", async () => { + const { patchJsonTextDetailed } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ",", + keySeparator: ": ", + ensureAscii: false + } + const previous = `{ + "a": "untouched", + "metadata": { + "x": 1 + } +}` + const result = patchJsonTextDetailed( + previous, + { a: "untouched", metadata: { y: 2 } }, + { style } + ) + expect(result.reason).toBeUndefined() + expect(result.text).toBe(`{ + "a": "untouched", + "metadata": { + "y": 2 + } +}`) + }) + + it("anchors an added key before the first surviving key that sorts after it", async () => { + const { patchJsonTextDetailed } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + const previous = `{ + "z": 1, + "a": 2 +}` + const result = patchJsonTextDetailed(previous, { z: 1, a: 2, c: 3 }, { style }) + expect(result.reason).toBeUndefined() + expect(result.text).toBe(`{ + "c": 3, + "z": 1, + "a": 2 +}`) + }) + + it("keeps an added container value inline when its object is inline", async () => { + const { patchJsonTextDetailed } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + const previous = `{ + "inline": {"a": 1}, + "other": 2 +}` + const result = patchJsonTextDetailed( + previous, + { inline: { a: 1, arr: [1, 2] }, other: 2 }, + { style } + ) + expect(result.reason).toBeUndefined() + expect(result.text).toBe(`{ + "inline": {"a": 1, "arr": [1, 2]}, + "other": 2 +}`) + }) + + it("keeps an added container value multiline when its object is multiline", async () => { + const { patchJsonTextDetailed } = await import("../../src/utils/json-patch.js") + const style = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false + } + const previous = `{ + "block": { + "a": 1 + }, + "other": 2 +}` + const result = patchJsonTextDetailed( + previous, + { block: { a: 1, arr: [1, 2] }, other: 2 }, + { style } + ) + expect(result.reason).toBeUndefined() + expect(result.text).toBe(`{ + "block": { + "a": 1, + "arr": [ + 1, + 2 + ] + }, + "other": 2 +}`) + }) +}) diff --git a/test/unit/notebook-text-shape.test.ts b/test/unit/notebook-text-shape.test.ts new file mode 100644 index 0000000..110c795 --- /dev/null +++ b/test/unit/notebook-text-shape.test.ts @@ -0,0 +1,299 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { + makeExecutionImpl, + makeNotebookFileService, + makePathService, + makePermissionService +} from "../../src/services/index.js" +import { textShapeOfCell } from "../../src/services/NotebookExecutionService.js" +import type { KernelManagerShape } from "../../src/services/KernelManager.js" +import type { PythonServiceShape } from "../../src/services/PythonService.js" +import type { ToolContext } from "../../src/tool.js" + +const ctx = (d: string) => ({ + sessionID: "t", messageID: "t", agent: "t", directory: d, worktree: d, + abort: new AbortController().signal, metadata: () => {}, ask: async () => {} +}) as unknown as ToolContext + +const pythonSvc = { + probe: () => Effect.succeed({ pythonPath: "/usr/bin/python3", version: "3", executable: "python3", from: "options" as const }), + findHelper: () => Effect.succeed("/tmp/ipynb_runner.py"), + checkDependencies: () => Effect.succeed([]), + candidates: () => Effect.succeed([]), + checkImport: () => Effect.succeed({ name: "x", available: true, detail: "ok" }), + doctor: () => Effect.succeed({} as never) +} as unknown as PythonServiceShape + +const run = async (e: Effect.Effect) => Effect.runPromise(e as Effect.Effect) + +describe("text shape is decided per cell", () => { + it("ignores application/json arrays, which nbformat never splits", () => { + const cell = { + cell_type: "code", execution_count: null, metadata: {}, source: "x", + outputs: [{ output_type: "display_data", data: { "application/json": [{ a: 1 }] } }] + } + expect(textShapeOfCell(cell as never, "arrays")).toBe("strings") + }) + + it("classifies a cell by its own text, not the notebook", () => { + const arrayCell = { + cell_type: "code", execution_count: 1, metadata: {}, source: ["x"], + outputs: [{ output_type: "stream", name: "stdout", text: ["a\n"] }] + } + const stringCell = { + cell_type: "code", execution_count: 1, metadata: {}, source: ["x"], + outputs: [{ output_type: "stream", name: "stdout", text: "a\n" }] + } + expect(textShapeOfCell(arrayCell as never, "strings")).toBe("arrays") + expect(textShapeOfCell(stringCell as never, "arrays")).toBe("strings") + }) + + it("falls back to the cell source, then the notebook shape", () => { + const noOutputs = { + cell_type: "code", execution_count: null, metadata: {}, source: ["x"], outputs: [] + } + expect(textShapeOfCell(noOutputs as never, "strings")).toBe("arrays") + const bare = { cell_type: "code", metadata: {}, outputs: [] } as never + expect(textShapeOfCell(bare, "arrays")).toBe("arrays") + expect(textShapeOfCell(bare, "strings")).toBe("strings") + }) +}) + +describe("ipynb_run save keeps each cell's own text shape", () => { + const saveWith = async (text: string, executed: number[], rawByCell: Map) => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "shape-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, text) + try { + const kernel = { + execute: () => Effect.succeed({ + success: true, + executedCells: executed, + durationMs: 1, + outputs: executed.map((idx) => ({ + cellIndex: idx, status: "ok" as const, executionCount: 1, + rawOutputs: rawByCell.get(idx) ?? [], + stdout: "x\n" + })) + }) + } as unknown as KernelManagerShape + const exec = makeExecutionImpl( + makePathService({ directory: dir, worktree: dir, platform: process.platform }), + makeNotebookFileService(), + makePermissionService(ctx(dir)), + pythonSvc, + { kernelManager: kernel, warmKernel: true, defaultTimeoutMs: 30_000 } + ) + await run(exec.execute(file, { + mode: "all", cellIndex: undefined, start: undefined, end: undefined, + kernel: undefined, timeoutMs: 30_000, save: true, + workingDirectory: undefined, maxOutputChars: 4_000 + })) + return JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ outputs: Array> }> + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + } + + it("splits a cell that stored arrays", async () => { + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "old\\n" + ] + } + ], + "source": [ + "a" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + const raw = [{ name: "stdout", output_type: "stream", text: "new\nline\n" }] + const out = await saveWith(text, [0], new Map([[0, raw]])) + expect(out.cells[0]?.outputs[0]?.text).toEqual(["new\n", "line\n"]) + }) + + it("keeps strings when the executed cell stored strings, even if another cell has an array", async () => { + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": "old\\n" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "stray\\n" + ] + } + ], + "source": [ + "b" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + const raw = [{ name: "stdout", output_type: "stream", text: "new\nline\n" }] + const out = await saveWith(text, [0], new Map([[0, raw]])) + expect(out.cells[0]?.outputs[0]?.text).toBe("new\nline\n") + }) + + it("restores each output's own shape instead of the cell majority", async () => { + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": "old\\n" + }, + { + "name": "stdout", + "output_type": "stream", + "text": [ + "older\\n" + ] + } + ], + "source": [ + "a" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + const raw = [ + { name: "stdout", output_type: "stream", text: "new-a\n" }, + { name: "stdout", output_type: "stream", text: "new-b\n" } + ] + const out = await saveWith(text, [0], new Map([[0, raw]])) + expect(out.cells[0]?.outputs[0]?.text).toBe("new-a\n") + expect(out.cells[0]?.outputs[1]?.text).toEqual(["new-b\n"]) + }) + + it("restores each data mime value to its own shape", async () => { + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "output_type": "display_data", + "data": { + "text/plain": "plain" + } + }, + { + "output_type": "display_data", + "data": { + "text/html": [ + "old\\n" + ] + } + } + ], + "source": [ + "a" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + const raw = [ + { output_type: "display_data", data: { "text/plain": "np" } }, + { output_type: "display_data", data: { "text/html": "new\n" } } + ] + const out = await saveWith(text, [0], new Map([[0, raw]])) + const first = out.cells[0]?.outputs[0] as { data: Record } + const second = out.cells[0]?.outputs[1] as { data: Record } + expect(first.data["text/plain"]).toBe("np") + expect(second.data["text/html"]).toEqual(["new\n"]) + }) + + it("uses the cell shape for an output position that did not exist before", async () => { + const text = `{ + "cells": [ + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "old\\n" + ] + } + ], + "source": [ + "a" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + const raw = [ + { name: "stdout", output_type: "stream", text: "a\n" }, + { name: "stdout", output_type: "stream", text: "b\n" } + ] + const out = await saveWith(text, [0], new Map([[0, raw]])) + expect(out.cells[0]?.outputs[0]?.text).toEqual(["a\n"]) + expect(out.cells[0]?.outputs[1]?.text).toEqual(["b\n"]) + }) +}) diff --git a/test/unit/notebook-write-order.test.ts b/test/unit/notebook-write-order.test.ts new file mode 100644 index 0000000..aae136b --- /dev/null +++ b/test/unit/notebook-write-order.test.ts @@ -0,0 +1,583 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { + makeCleanImpl, + makeEditImpl, + makeExecutionImpl, + makeNotebookFileService, + makeOutputImpl, + makePathService, + makePermissionService +} from "../../src/services/index.js" +import type { CodeCellRaw } from "../../src/domain/cell.js" +import type { KernelManagerShape } from "../../src/services/KernelManager.js" +import type { PythonServiceShape } from "../../src/services/PythonService.js" +import type { ToolContext } from "../../src/tool.js" + +const makeFakeContext = (directory: string, worktree: string): ToolContext => + ({ + sessionID: "test", + messageID: "test", + agent: "test", + directory, + worktree, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + }) as unknown as ToolContext + +const runOrThrow = async ( + effect: Effect.Effect +): Promise => Effect.runPromise(effect as Effect.Effect) + +/** + * The notebook convention described in issue #2: `json.dumps(..., sort_keys=True, + * indent=1)`, which is what nbformat's writer, VS Code, and Databricks produce. + * Insertion order below is already alphabetical so the stored text is realistic. + */ +const storedNotebook = (): Record => ({ + cells: [ + { + cell_type: "markdown", + id: "intro", + metadata: { + "application/vnd.databricks.v1+cell": { showTitle: false } + }, + source: ["# Title"] + }, + { + cell_type: "code", + execution_count: 1, + id: "code", + metadata: {}, + outputs: [ + { name: "stdout", output_type: "stream", text: ["hi\n"] } + ], + source: ["print(1)\n", "print(2)"] + } + ], + metadata: { language_info: { name: "python" } }, + nbformat: 4, + nbformat_minor: 4 +}) + +const writeStored = (file: string): void => { + fs.writeFileSync(file, `${JSON.stringify(storedNotebook(), null, 1)}\n`) +} + +const TOP_LEVEL_ORDER = ["cells", "metadata", "nbformat", "nbformat_minor"] +const CODE_CELL_ORDER = [ + "cell_type", + "execution_count", + "id", + "metadata", + "outputs", + "source" +] + +const setup = (dir: string) => { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const fileSvc = makeNotebookFileService() + const permSvc = makePermissionService(makeFakeContext(dir, dir)) + return { + pathSvc, + fileSvc, + permSvc, + edit: makeEditImpl(pathSvc, fileSvc, permSvc), + output: makeOutputImpl(pathSvc, fileSvc, permSvc), + clean: makeCleanImpl(pathSvc, fileSvc, permSvc) + } +} + +describe("NotebookFileService key order", () => { + it("returns the raw parsed JSON instead of the zod-rebuilt object", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-read-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { fileSvc } = setup(dir) + const snapshot = await runOrThrow(fileSvc.readWithText(file)) + expect(Object.keys(snapshot.notebook)).toEqual(TOP_LEVEL_ORDER) + expect(Object.keys(snapshot.notebook.cells[1] as unknown as object)).toEqual( + CODE_CELL_ORDER + ) + expect( + Object.keys((snapshot.notebook.cells[1] as CodeCellRaw).outputs[0] as object) + ).toEqual(["name", "output_type", "text"]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("ipynb_edit byte stability", () => { + it("preserves the notebook's existing indentation", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-indent-")) + const file = path.join(dir, "stored.ipynb") + const twoSpace = `${JSON.stringify(storedNotebook(), null, 2)}\n` + fs.writeFileSync(file, twoSpace) + try { + const { edit } = setup(dir) + const expected = storedNotebook() + ;(expected.cells as Array<{ source: string | string[] }>)[1]!.source = [ + "print(1)\n", + "print(22)" + ] + await runOrThrow( + edit.editCell(file, { + cellIndex: 1, + source: "print(1)\nprint(22)", + clearOutputs: "never" + }) + ) + expect(fs.readFileSync(file, "utf8")).toBe( + `${JSON.stringify(expected, null, 2)}\n` + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("preserves tab indentation and a missing trailing newline", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-indent-")) + const file = path.join(dir, "stored.ipynb") + const tabbed = JSON.stringify(storedNotebook(), null, "\t") + fs.writeFileSync(file, tabbed) + try { + const { edit } = setup(dir) + const expected = storedNotebook() + ;(expected.cells as Array<{ source: string | string[] }>)[0]!.source = [ + "# Edited" + ] + await runOrThrow( + edit.editCell(file, { + cellIndex: 0, + source: "# Edited", + clearOutputs: "never" + }) + ) + expect(fs.readFileSync(file, "utf8")).toBe( + JSON.stringify(expected, null, "\t") + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("only changes the edited cell's bytes and keeps nbformat key order", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-edit-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { edit } = setup(dir) + const before = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[] }> + } + const result = await runOrThrow( + edit.editCell(file, { + cellIndex: 1, + source: "print(1)\nprint(22)", + clearOutputs: "never" + }) + ) + expect(result.changed).toBe(true) + const expected = before + expected.cells[1]!.source = ["print(1)\n", "print(22)"] + expect(fs.readFileSync(file, "utf8")).toBe( + `${JSON.stringify(expected, null, 1)}\n` + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("keeps array source shape when the notebook stores line arrays", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-array-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { edit } = setup(dir) + const result = await runOrThrow( + edit.editCell(file, { + cellIndex: 1, + source: "print(1)\nprint(22)", + clearOutputs: "never" + }) + ) + const cell = result.notebook.cells[1] as CodeCellRaw + expect(Array.isArray(cell.source)).toBe(true) + expect(cell.source).toEqual(["print(1)\n", "print(22)"]) + const onDisk = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[] }> + } + expect(onDisk.cells[1]?.source).toEqual(["print(1)\n", "print(22)"]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("keeps string source shape when the notebook stores a single string", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-string-")) + const file = path.join(dir, "stored.ipynb") + const stored = { + cells: [ + { cell_type: "markdown", metadata: {}, source: "# A" }, + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "print(1)" + } + ], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + } + fs.writeFileSync(file, `${JSON.stringify(stored, null, 1)}\n`) + try { + const { edit } = setup(dir) + await runOrThrow( + edit.editCell(file, { + cellIndex: 0, + source: "# B\n\nMore", + clearOutputs: "never" + }) + ) + const expected = { + ...stored, + cells: [ + { cell_type: "markdown", metadata: {}, source: "# B\n\nMore" }, + stored.cells[1] + ] + } + const onDisk = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[] }> + } + expect(typeof onDisk.cells[0]?.source).toBe("string") + expect(onDisk.cells[0]?.source).toBe("# B\n\nMore") + expect(fs.readFileSync(file, "utf8")).toBe( + `${JSON.stringify(expected, null, 1)}\n` + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("keeps key order when auto-clearing outputs and execution_count", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-clear-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { edit } = setup(dir) + const result = await runOrThrow( + edit.editCell(file, { cellIndex: 1, source: "print(3)" }) + ) + expect(result.clearedOutputs).toBe(true) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ execution_count: unknown; outputs: unknown[]; source: unknown }> + } + expect(after.cells[1]?.execution_count).toBeNull() + expect(after.cells[1]?.outputs).toEqual([]) + expect(after.cells[1]?.source).toEqual(["print(3)"]) + expect(Object.keys(after)).toEqual(TOP_LEVEL_ORDER) + expect(Object.keys(after.cells[1] as unknown as object)).toEqual( + CODE_CELL_ORDER + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("other notebook writers keep key order", () => { + it("ipynb_cell_insert keeps top-level order and untouched cell order", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-insert-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { edit } = setup(dir) + await runOrThrow(edit.insertCell(file, "markdown", "# Inserted", 1)) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: unknown[] + } + expect(after.cells.length).toBe(3) + expect(Object.keys(after)).toEqual(TOP_LEVEL_ORDER) + expect(Object.keys(after.cells[0] as object)).toEqual([ + "cell_type", + "id", + "metadata", + "source" + ]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("a newly inserted code cell uses the nbformat key order", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-insert-code-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { edit } = setup(dir) + await runOrThrow(edit.insertCell(file, "code", "print(9)", 0)) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: unknown[] + } + expect(Object.keys(after.cells[0] as object)).toEqual([ + "cell_type", + "execution_count", + "metadata", + "outputs", + "source" + ]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("newly inserted markdown and raw cells use the nbformat key order", async () => { + for (const [cellType, prefix] of [ + ["markdown", "md"], + ["raw", "raw"] + ] as const) { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), `ipynb-order-insert-${prefix}-`)) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { edit } = setup(dir) + await runOrThrow(edit.insertCell(file, cellType, "body", 0)) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: unknown[] + } + const keys = Object.keys(after.cells[0] as object) + expect(keys.indexOf("cell_type")).toBe(0) + expect(keys.indexOf("metadata")).toBeLessThan(keys.indexOf("source")) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + } + }) + + it("ipynb_outputs clear_cell clears the cell and keeps order", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-outputs-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { output } = setup(dir) + await runOrThrow(output.clearCellOutputs(file, 1)) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ outputs: unknown[]; execution_count: unknown }> + } + expect(after.cells[1]?.outputs).toEqual([]) + expect(after.cells[1]?.execution_count).toBeNull() + expect(Object.keys(after)).toEqual(TOP_LEVEL_ORDER) + expect(Object.keys(after.cells[1] as unknown as object)).toEqual( + CODE_CELL_ORDER + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("ipynb_outputs clear_all keeps untouched bytes", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-clearall-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { output } = setup(dir) + await runOrThrow(output.clearAllOutputs(file)) + const raw = fs.readFileSync(file, "utf8") + expect(Object.keys(JSON.parse(raw))).toEqual(TOP_LEVEL_ORDER) + expect(raw).toContain('"id": "intro"') + expect(raw).toContain('"application/vnd.databricks.v1+cell": {') + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("ipynb_clean normalizeSource=false keeps source arrays and order", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-clean-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { clean } = setup(dir) + const result = await runOrThrow( + clean.clean(file, { + clearOutputs: false, + clearExecutionCount: false, + stripWidgetState: false, + stripLargeImages: false, + normalizeSource: false + }) + ) + expect(result.affectedCells).toBe(0) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[] }> + } + expect(Array.isArray(after.cells[1]?.source)).toBe(true) + expect(Object.keys(after)).toEqual(TOP_LEVEL_ORDER) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("ipynb_clean's default normalizeSource rewrites arrays to strings", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-clean2-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { clean } = setup(dir) + await runOrThrow(clean.clean(file)) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[] }> + } + expect(typeof after.cells[0]?.source).toBe("string") + expect(Object.keys(after)).toEqual(TOP_LEVEL_ORDER) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("ipynb_run save=true keeps top-level order and untouched cells", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-run-")) + const file = path.join(dir, "stored.ipynb") + writeStored(file) + try { + const { pathSvc, fileSvc, permSvc } = setup(dir) + const pythonSvc = { + probe: () => + Effect.succeed({ + pythonPath: "/usr/bin/python3", + version: "3", + executable: "python3", + from: "options" as const + }), + findHelper: () => Effect.succeed("/tmp/ipynb_runner.py"), + checkDependencies: () => Effect.succeed([]), + candidates: () => Effect.succeed([]), + checkImport: () => Effect.succeed({ name: "x", available: true, detail: "ok" }), + doctor: () => Effect.succeed({} as never) + } as unknown as PythonServiceShape + const kernel = { + execute: () => + Effect.succeed({ + success: true, + executedCells: [1], + durationMs: 1, + outputs: [ + { + cellIndex: 1, + status: "ok" as const, + stdout: "hello\n", + executionCount: 3 + } + ] + }) + } as unknown as KernelManagerShape + const exec = makeExecutionImpl(pathSvc, fileSvc, permSvc, pythonSvc, { + kernelManager: kernel, + warmKernel: true, + defaultTimeoutMs: 30_000 + }) + const result = await runOrThrow( + exec.execute(file, { + mode: "cell", + cellIndex: 1, + start: undefined, + end: undefined, + kernel: undefined, + timeoutMs: 30_000, + save: true, + workingDirectory: undefined, + maxOutputChars: 4_000 + }) + ) + expect(result.saved).toBe(true) + const after = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ execution_count: unknown; outputs: unknown[] }> + } + expect(Object.keys(after)).toEqual(TOP_LEVEL_ORDER) + expect(Object.keys(after.cells[0] as unknown as object)).toEqual([ + "cell_type", + "id", + "metadata", + "source" + ]) + expect(Object.keys(after.cells[1] as unknown as object)).toEqual( + CODE_CELL_ORDER + ) + expect(after.cells[1]?.execution_count).toBe(3) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("line endings", () => { + it("preserves CRLF notebooks instead of rewriting every line", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-crlf-")) + const file = path.join(dir, "stored.ipynb") + const crlf = `${JSON.stringify(storedNotebook(), null, 1)}\n`.replace( + /\n/g, + "\r\n" + ) + fs.writeFileSync(file, crlf) + try { + const { edit } = setup(dir) + const expected = storedNotebook() + ;(expected.cells as Array<{ source: string | string[] }>)[1]!.source = [ + "print(1)\n", + "print(22)" + ] + await runOrThrow( + edit.editCell(file, { + cellIndex: 1, + source: "print(1)\nprint(22)", + clearOutputs: "never" + }) + ) + const after = fs.readFileSync(file, "utf8") + expect(after.includes("\r\n")).toBe(true) + expect(after).not.toContain("\r\r\n") + expect((after.match(/\r\n/g) ?? []).length).toBe( + (after.match(/\n/g) ?? []).length + ) + expect(after.replace(/\r\n/g, "\n")).toBe( + `${JSON.stringify(expected, null, 1)}\n` + ) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("re-serializes a CRLF notebook without doubling carriage returns", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-order-crlf2-")) + const file = path.join(dir, "stored.ipynb") + const crlf = `${JSON.stringify(storedNotebook(), null, 1)}\n`.replace( + /\n/g, + "\r\n" + ) + fs.writeFileSync(file, crlf) + try { + const { edit } = setup(dir) + // Deleting the first cell takes the re-serialization path. + await runOrThrow(edit.deleteCell(file, 0)) + const after = fs.readFileSync(file, "utf8") + expect(after).not.toContain("\r\r\n") + expect((after.match(/\r\n/g) ?? []).length).toBe( + (after.match(/\n/g) ?? []).length + ) + expect(JSON.parse(after).cells.length).toBe(1) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/notebook.test.ts b/test/unit/notebook.test.ts index 47a31d6..b77eb34 100644 --- a/test/unit/notebook.test.ts +++ b/test/unit/notebook.test.ts @@ -1,5 +1,5 @@ import { describe, expect, it } from "bun:test" -import { Effect } from "effect" +import { Cause, Effect } from "effect" import * as path from "node:path" import * as fs from "node:fs" import * as os from "node:os" @@ -15,6 +15,7 @@ import { } from "../../src/services/index.js" import { CellIndexOutOfBoundsError, NotebookNotFoundError, NotebookParseError, NotebookValidationError } from "../../src/domain/errors.js" import { buildServices } from "../../src/services/index.js" +import { makeWarningSink } from "../../src/utils/warnings.js" import { inspectCell } from "../../src/format/diagnostics.js" import { formatOutputs } from "../../src/format/outputs.js" import type { ToolContext } from "../../src/tool.js" @@ -81,6 +82,109 @@ describe("NotebookSchema validation", () => { fs.rmSync(dir, { recursive: true, force: true }) } }) + + it("rejects a UTF-8 BOM as a parse error like nbformat, leaving the file untouched", async () => { + const fileSvc = makeNotebookFileService() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-")) + const file = path.join(dir, "bom.ipynb") + const text = `\uFEFF${JSON.stringify({ + cells: [], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + })}` + fs.writeFileSync(file, text) + try { + const result = await Effect.runPromise( + fileSvc.read(file).pipe(Effect.flip) + ) + expect(result).toBeInstanceOf(NotebookParseError) + expect(fs.readFileSync(file, "utf8")).toBe(text) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("rejects bytes that are not valid UTF-8 instead of replacing them", async () => { + const fileSvc = makeNotebookFileService() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-")) + const file = path.join(dir, "latin1.ipynb") + const bytes = Buffer.from( + '{"cells":[],"metadata":{"name":"caf\xe9"},"nbformat":4,"nbformat_minor":5}', + "latin1" + ) + fs.writeFileSync(file, bytes) + try { + const result = await Effect.runPromise( + fileSvc.read(file).pipe(Effect.flip) + ) + expect(result).toBeInstanceOf(NotebookParseError) + expect(fs.readFileSync(file).equals(bytes)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("refuses to rewrite bytes that are not valid UTF-8", async () => { const fileSvc = makeNotebookFileService() + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-")) + const file = path.join(dir, "latin1.ipynb") + const bytes = Buffer.from( + '{"cells":[],"metadata":{"name":"caf\xe9"},"nbformat":4,"nbformat_minor":5}', + "latin1" + ) + fs.writeFileSync(file, bytes) + try { + const exit = await Effect.runPromiseExit( + fileSvc.writeAtomic(file, { + cells: [], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + } as never) + ) + expect(exit._tag).toBe("Failure") + const error = exit._tag === "Failure" ? Cause.findErrorOption(exit.cause) : undefined + expect(error?._tag === "Some" ? error.value : undefined).toBeInstanceOf( + NotebookParseError + ) + expect(fs.readFileSync(file).equals(bytes)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("resolves a real path through the retrying helper and still reports a genuine miss", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-realpath-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync( + file, + JSON.stringify({ cells: [], metadata: {}, nbformat: 4, nbformat_minor: 5 }) + ) + try { + const { realpathWithRetry } = await import("../../src/utils/realpath.js") + // Windows spells one file several ways (8.3 short names such as + // RUNNER~1) and the two resolution APIs disagree there, so compare what + // the path denotes instead of how it is spelled: a resolution that + // pointed anywhere else would fail the stat identity check. + const resolved = await realpathWithRetry(file) + expect(fs.existsSync(resolved)).toBe(true) + expect(fs.statSync(resolved).ino).toBe(fs.statSync(file).ino) + expect(fs.statSync(resolved).dev).toBe(fs.statSync(file).dev) + const missing = path.join(dir, "missing.ipynb") + // A wall-clock budget here only measures runner load: on a loaded + // single-process suite run the three setImmediate-spaced attempts took + // 1.2 s for identical code, so the old 1 s ceiling was a lottery. The + // miss path itself is pinned structurally by the code (three attempts, + // no sleeps); this ceiling is a hang guard, far above any loaded runner + // and far below an actual spin. + const started = Date.now() + await expect(realpathWithRetry(missing)).rejects.toMatchObject({ code: "ENOENT" }) + expect(Date.now() - started).toBeLessThan(5_000) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + }) describe("Source normalization", () => { @@ -349,24 +453,35 @@ describe("Edit", () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-")) const file = path.join(dir, "test.ipynb") fs.copyFileSync(path.join(FIXTURES, "simple.ipynb"), file) - const pathSvc = makePathService({ - directory: dir, - worktree: dir, - platform: process.platform - }) - const fileSvc = makeNotebookFileService() - const permSvc = makePermissionService(makeFakeContext(dir, dir)) - const edit = makeEditImpl(pathSvc, fileSvc, permSvc) - const originalMeta = (() => { - const nb = JSON.parse(fs.readFileSync(file, "utf8")) as { cells: Array<{ cell_type: string; metadata: unknown }> } - return nb.cells[0]?.metadata - })() - const result = await runOrThrow(edit.editCell(file, { cellIndex: 0, source: "# New title\n\nUpdated." })) - expect(result.cellType).toBe("markdown") - expect(result.clearedOutputs).toBe(false) - expect(result.notebook.cells[0]?.metadata as object).toEqual(originalMeta as object) - expect((result.notebook.cells[0] as { source: string }).source).toBe("# New title\n\nUpdated.") - fs.rmSync(dir, { recursive: true, force: true }) + try { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const fileSvc = makeNotebookFileService() + const permSvc = makePermissionService(makeFakeContext(dir, dir)) + const edit = makeEditImpl(pathSvc, fileSvc, permSvc) + const originalMeta = (() => { + const nb = JSON.parse(fs.readFileSync(file, "utf8")) as { cells: Array<{ cell_type: string; metadata: unknown }> } + return nb.cells[0]?.metadata + })() + const result = await runOrThrow(edit.editCell(file, { cellIndex: 0, source: "# New title\n\nUpdated." })) + expect(result.cellType).toBe("markdown") + expect(result.clearedOutputs).toBe(false) + expect(result.notebook.cells[0]?.metadata as object).toEqual(originalMeta as object) + expect((result.notebook.cells[0] as { source: string[] }).source).toEqual([ + "# New title\n", + "\n", + "Updated." + ]) + const onDisk = JSON.parse(fs.readFileSync(file, "utf8")) as { + cells: Array<{ source: string | string[] }> + } + expect(onDisk.cells[0]?.source).toEqual(["# New title\n", "\n", "Updated."]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } }) it("clears outputs on a code cell when source changes (auto)", async () => { @@ -651,3 +766,248 @@ describe("inspectCell > large streams", () => { expect(inspected.hasLargeOutput).toBe(true) }) }) + +describe("write refusal on unreadable targets", () => { + it("refuses to overwrite a notebook it cannot read", async () => { + if (process.platform === "win32") return + if (typeof process.getuid === "function" && process.getuid() === 0) return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-unreadable-")) + const file = path.join(dir, "n.ipynb") + const original = `${JSON.stringify( + { cells: [], metadata: { secret: "keep-me" }, nbformat: 4, nbformat_minor: 5 }, + null, + 1 + )}\n` + fs.writeFileSync(file, original) + fs.chmodSync(file, 0o000) + const sink = makeWarningSink() + const svc = makeNotebookFileService({ worktree: dir, warningSink: sink }) + try { + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, { + cells: [], + metadata: { replaced: true }, + nbformat: 4, + nbformat_minor: 5 + } as never) + ) + expect(exit._tag).toBe("Failure") + fs.chmodSync(file, 0o600) + expect(fs.readFileSync(file, "utf8")).toBe(original) + } finally { + fs.chmodSync(file, 0o600) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("still creates a notebook that does not exist yet", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-create-")) + const file = path.join(dir, "new.ipynb") + const svc = makeNotebookFileService({ worktree: dir }) + try { + const outcome = await Effect.runPromise( + svc.writeAtomic(file, { + cells: [], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + } as never) + ) + expect(outcome.mode).toBe("fallback") + expect(JSON.parse(fs.readFileSync(file, "utf8"))).toBeDefined() + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("revision re-read failure refuses the write", () => { + it("does not write when the pre-rename revision read fails", async () => { + if (process.platform === "win32") return + if (typeof process.getuid === "function" && process.getuid() === 0) return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-revision-fail-")) + const file = path.join(dir, "n.ipynb") + const body = `${JSON.stringify( + { cells: [], metadata: { keep: true }, nbformat: 4, nbformat_minor: 5 }, + null, + 1 + )}\n` + const sink = makeWarningSink() + try { + const svc = makeNotebookFileService({ worktree: dir, warningSink: sink }) + const read = await Effect.runPromise(svc.readWithText(file).pipe(Effect.orElseSucceed(() => undefined))) + void read + fs.writeFileSync(file, body) + const before = fs.readFileSync(file) + fs.chmodSync(file, 0o000) + try { + const exit = await Effect.runPromiseExit( + svc.writeAtomic( + file, + { cells: [], metadata: { replaced: true }, nbformat: 4, nbformat_minor: 5 } as never, + { + previousText: body, + format: { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false, + trailingNewline: true + } + } + ) + ) + expect(exit._tag).toBe("Failure") + } finally { + fs.chmodSync(file, 0o600) + } + expect(fs.readFileSync(file).equals(before)).toBe(true) + } finally { + try { fs.chmodSync(file, 0o600) } catch {} + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("cells without execution_count", () => { + it("accepts and byte-stably rewrites a notebook nbformat.read accepts", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-noexec-")) + const file = path.join(dir, "n.ipynb") + const body = `{\n "cells": [\n {"cell_type": "code", "metadata": {}, "outputs": [], "source": ["x = 1"]}\n ],\n "metadata": {},\n "nbformat": 4,\n "nbformat_minor": 5\n}\n` + fs.writeFileSync(file, body) + const svc = makeNotebookFileService({ worktree: dir }) + try { + const read = await Effect.runPromise(svc.readWithText(file)) + expect(read.notebook.cells).toHaveLength(1) + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, read.notebook as never, { + format: read.format, + previousText: read.text + }) + ) + expect(exit._tag).toBe("Success") + expect(fs.readFileSync(file, "utf8")).toBe(body) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("union validation errors name the offending field", () => { + it("reports cells.0.cell_type instead of a bare 'Invalid input'", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-union-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync( + file, + JSON.stringify({ + cells: [{ cell_type: "codex", metadata: {}, source: ["x"] }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }) + ) + try { + const exit = await Effect.runPromiseExit( + makeNotebookFileService({ worktree: dir }).read(file) + ) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.findErrorOption(exit.cause) + const value = error._tag === "Some" ? error.value : undefined + expect(value).toBeInstanceOf(NotebookValidationError) + const issues = (value as { issues?: ReadonlyArray }).issues ?? [] + expect(issues.join(" | ")).toContain("cells.0.cell_type") + expect(issues.join(" | ")).toContain("markdown") + expect(issues).not.toContain("cells.0: Invalid input") + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("excessively nested values", () => { + it("refuses the write with the depth limit named and the file untouched", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-deep-")) + const file = path.join(dir, "n.ipynb") + const depth = 5_000 + const deep = "[".repeat(depth) + "]".repeat(depth) + const body = `{"cells": [{"cell_type": "markdown", "metadata": {}, "source": ["# A"]}], "metadata": {"deep": ${deep}}, "nbformat": 4, "nbformat_minor": 5}\n` + fs.writeFileSync(file, body) + const before = fs.readFileSync(file) + const svc = makeNotebookFileService({ worktree: dir }) + try { + const read = await Effect.runPromise(svc.readWithText(file)) + const edited = read.notebook as unknown as { + cells: Array> + metadata: Record + } + edited.cells[0] = { ...edited.cells[0], source: ["# B"] } + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, read.notebook as never, { + format: read.format, + previousText: read.text + }) + ) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.findErrorOption(exit.cause) + const value = error._tag === "Some" ? error.value : undefined + expect(value).toBeInstanceOf(NotebookValidationError) + expect((value as { message?: string }).message ?? "").toContain("nesting") + expect((value as { message?: string }).message ?? "").toContain("512") + } + expect(fs.readFileSync(file).equals(before)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) + +describe("unrepresentable notebook values", () => { + it("refuses the write with an actionable message instead of dropping the field", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-undef-")) + const file = path.join(dir, "n.ipynb") + const body = `${JSON.stringify( + { cells: [], metadata: { keep: 1 }, nbformat: 4, nbformat_minor: 5 }, + null, + 1 + )}\n` + fs.writeFileSync(file, body) + const before = fs.readFileSync(file) + try { + const svc = makeNotebookFileService({ worktree: dir }) + const exit = await Effect.runPromiseExit( + svc.writeAtomic( + file, + { cells: [], metadata: { keep: 1, gone: undefined }, nbformat: 4, nbformat_minor: 5 } as never, + { + trusted: true, + format: { + unit: " ", + newline: "\n", + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false, + trailingNewline: true + } + } + ) + ) + expect(exit._tag).toBe("Failure") + if (exit._tag === "Failure") { + const error = Cause.findErrorOption(exit.cause) + const value = error._tag === "Some" ? error.value : undefined + expect(value).toBeInstanceOf(NotebookValidationError) + expect((value as { message?: string }).message ?? "").toContain("serialized to JSON") + const issues = (value as { issues?: ReadonlyArray }).issues ?? [] + expect(issues.join(" ")).toContain("undefined, BigInt, cyclic") + } + expect(fs.readFileSync(file).equals(before)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/parent-swap-confinement.test.ts b/test/unit/parent-swap-confinement.test.ts new file mode 100644 index 0000000..9b22f7e --- /dev/null +++ b/test/unit/parent-swap-confinement.test.ts @@ -0,0 +1,174 @@ +import { afterEach, describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { buildNotebookVirtualDocument } from "../../src/lsp.js" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { materializeVirtualDocument } from "../../src/virtual-materialize.js" +import { setBeforeRenameHook } from "../../src/utils/rename-hook.js" + +const notebook = (source: string): string => + `${JSON.stringify( + { + cells: [{ cell_type: "markdown", metadata: {}, source: [source] }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 + )}\n` + +const format = { + unit: " ", + newline: "\n" as const, + itemSeparator: ", ", + keySeparator: ": ", + ensureAscii: false, + trailingNewline: true +} + +afterEach(() => { + setBeforeRenameHook(undefined) +}) + +describe("a parent directory swapped immediately before the rename", () => { + it("does not write the notebook outside the worktree", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-swap-")) + const outside = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-swap-out-")) + const sub = path.join(dir, "sub") + fs.mkdirSync(sub) + const file = path.join(sub, "n.ipynb") + fs.writeFileSync(file, notebook("# A")) + let swapped = false + setBeforeRenameHook(() => { + if (swapped) return + swapped = true + const parked = path.join(dir, "sub-parked") + fs.renameSync(sub, parked) + fs.symlinkSync(outside, sub) + for (const entry of fs.readdirSync(parked)) { + if (entry.endsWith(".tmp")) { + fs.copyFileSync(path.join(parked, entry), path.join(outside, entry)) + } + } + }) + try { + const svc = makeNotebookFileService({ worktree: dir }) + const read = await Effect.runPromise(svc.readWithText(file)) + const edited = { + ...read.notebook, + cells: [{ cell_type: "markdown", metadata: {}, source: ["# B"] }] + } + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, edited as never, { + format, + previousText: read.text + }) + ) + expect(swapped).toBe(true) + expect(exit._tag).toBe("Failure") + expect(fs.readdirSync(outside).filter((name) => name === "n.ipynb")).toEqual([]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + fs.rmSync(outside, { recursive: true, force: true }) + } + }) +}) + +describe("a parent directory swapped for sidecar materialization", () => { + it("does not write the sidecar outside the worktree", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-swap-sidecar-")) + const outside = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-swap-sidecar-out-")) + const sub = path.join(dir, "sub") + fs.mkdirSync(sub) + const file = path.join(sub, "n.ipynb") + fs.writeFileSync(file, notebook("# A")) + let swapped = false + setBeforeRenameHook(() => { + if (swapped) return + swapped = true + const parked = path.join(dir, "sub-parked") + fs.renameSync(sub, parked) + fs.symlinkSync(outside, sub) + for (const entry of fs.readdirSync(parked)) { + if (entry.endsWith(".tmp")) { + fs.copyFileSync(path.join(parked, entry), path.join(outside, entry)) + } + } + }) + try { + const document = buildNotebookVirtualDocument( + JSON.parse(notebook("# A")) as never, + { filePath: file } + ) + try { + await materializeVirtualDocument(document, dir) + } catch { + // a refusal is the expected outcome + } + expect(swapped).toBe(true) + const escaped = fs + .readdirSync(outside) + .filter((name) => name.startsWith("opencode-ipynb-lsp-") && name.endsWith(".py")) + expect(escaped).toEqual([]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + fs.rmSync(outside, { recursive: true, force: true }) + } + }) +}) + +describe("a failed parent-swap write leaves no temp behind", () => { + it("removes the temp even when it moved with the directory", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-swap-temp-")) + const outside = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-swap-temp-out-")) + const sub = path.join(dir, "sub") + fs.mkdirSync(sub) + const file = path.join(sub, "n.ipynb") + fs.writeFileSync(file, notebook("# A")) + setBeforeRenameHook(() => { + const parked = path.join(dir, "parked") + fs.renameSync(sub, parked) + fs.symlinkSync(outside, sub) + // The attacker copies the temp so the writer's rename can still find a + // source; the replace then fails against the re-validated directory and + // the cleanup must not leave the notebook content behind. + for (const entry of fs.readdirSync(parked)) { + if (entry.endsWith(".tmp")) { + fs.copyFileSync(path.join(parked, entry), path.join(outside, entry)) + } + } + }) + const temps = (root: string): string[] => + fs.readdirSync(root, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(root, entry.name) + if (entry.isDirectory()) return temps(full) + return entry.name.endsWith(".tmp") ? [full] : [] + }) + try { + const svc = makeNotebookFileService({ worktree: dir }) + const read = await Effect.runPromise(svc.readWithText(file)) + const edited = { + ...read.notebook, + cells: [{ cell_type: "markdown", metadata: {}, source: ["# B"] }] + } + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, edited as never, { + format, + previousText: read.text + }) + ) + expect(exit._tag).toBe("Failure") + expect(temps(dir)).toEqual([]) + } finally { + setBeforeRenameHook(undefined) + fs.rmSync(dir, { recursive: true, force: true }) + fs.rmSync(outside, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/path-confinement-windows.test.ts b/test/unit/path-confinement-windows.test.ts new file mode 100644 index 0000000..7eff66b --- /dev/null +++ b/test/unit/path-confinement-windows.test.ts @@ -0,0 +1,44 @@ +import { describe, expect, it } from "bun:test" +import * as os from "node:os" +import { Effect } from "effect" +import { makePathService } from "../../src/services/PathService.js" +import { absoluteDriveRoot } from "../../src/utils/paths.js" + +describe("absoluteDriveRoot", () => { + it("turns a bare drive into an absolute root on win32 only", () => { + expect(absoluteDriveRoot("C:", "win32")).toBe("C:\\") + expect(absoluteDriveRoot("d:", "win32")).toBe("d:\\") + expect(absoluteDriveRoot("C:\\", "win32")).toBe("C:\\") + expect(absoluteDriveRoot("C:\\Windows", "win32")).toBe("C:\\Windows") + expect(absoluteDriveRoot("/home/x", "win32")).toBe("/home/x") + expect(absoluteDriveRoot("", "win32")).toBe("") + expect(absoluteDriveRoot("C:", "linux")).toBe("C:") + }) +}) + +describe("worktree confinement on windows", () => { + it("rejects drive roots and other drives", async () => { + if (process.platform !== "win32") return + const worktree = os.tmpdir() + const svc = makePathService({ + directory: worktree, + worktree, + platform: process.platform + }) + const rejected = [ + "C:\\", + "C:\\etc\\outside.ipynb", + "D:\\nope\\outside.ipynb" + ] + for (const candidate of rejected) { + const exit = await Effect.runPromiseExit( + svc.ensureInsideWorktree(candidate) + ) + expect(exit._tag).toBe("Failure") + } + const inside = await Effect.runPromiseExit( + svc.ensureInsideWorktree(`${worktree}\\ok.ipynb`) + ) + expect(inside._tag).toBe("Success") + }) +}) diff --git a/test/unit/permission-aliases.test.ts b/test/unit/permission-aliases.test.ts index 5f72c8a..134ff27 100644 --- a/test/unit/permission-aliases.test.ts +++ b/test/unit/permission-aliases.test.ts @@ -6,6 +6,7 @@ import { permissionAliases } from "../../src/services/PermissionService.js" describe("permissionAliases", () => { it("returns both the lexical and real path for a symlink alias", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return if (process.platform === "win32") return const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-perm-alias-")) const real = path.join(dir, "real.ipynb") @@ -15,7 +16,9 @@ describe("permissionAliases", () => { try { const paths = await permissionAliases(alias, [dir]) expect(paths).toContain(alias) - expect(paths).toContain(real) + // The real alias comes back resolved; on macOS the temp dir itself is a + // symlink (/tmp -> /private/tmp), so the resolved spelling differs. + expect(paths).toContain(fs.realpathSync(real)) expect(paths).toContain("alias.ipynb") expect(paths).toContain("real.ipynb") } finally { @@ -24,6 +27,7 @@ describe("permissionAliases", () => { }) it("resolves the real parent for a new file under a symlinked directory", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return if (process.platform === "win32") return const root = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-perm-dir-")) const real = path.join(root, "real") @@ -33,7 +37,10 @@ describe("permissionAliases", () => { try { const paths = await permissionAliases(path.join(link, "new.ipynb")) expect(paths).toHaveLength(2) - expect(paths[1]).toBe(path.join(real, "new.ipynb")) + // The file does not exist yet, so resolve its parent: on macOS the temp + // dir itself is a symlink (/tmp -> /private/tmp) and a lexical compare + // reports a spurious mismatch. + expect(fs.realpathSync(path.dirname(paths[1]!))).toBe(fs.realpathSync(real)) } finally { fs.rmSync(root, { recursive: true, force: true }) } @@ -56,6 +63,7 @@ describe("permissionAliases", () => { }) it("resolves a not-yet-existing file through a symlinked ancestor", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return if (process.platform === "win32") return const root = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-perm-deep-")) const real = path.join(root, "real") @@ -66,7 +74,9 @@ describe("permissionAliases", () => { try { const paths = await permissionAliases(file, [root]) expect(paths).toContain(file) - expect(paths).toContain(path.join(real, "new", "out.py")) + // The file does not exist yet, but its parent does: expect the resolved + // spelling of the parent (macOS spells the temp dir through a symlink). + expect(paths).toContain(path.join(fs.realpathSync(real), "new", "out.py")) expect(paths).toContain(path.join("real", "new", "out.py")) } finally { fs.rmSync(root, { recursive: true, force: true }) diff --git a/test/unit/permission-denial.test.ts b/test/unit/permission-denial.test.ts new file mode 100644 index 0000000..f352b2f --- /dev/null +++ b/test/unit/permission-denial.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, it } from "bun:test" +import { Cause, Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { PermissionDeniedError } from "../../src/domain/errors.js" +import { + makeCleanImpl, + makeEditImpl, + makeNotebookFileService, + makeOutputImpl, + makePathService, + makePermissionService +} from "../../src/services/index.js" +import type { ToolContext } from "../../src/tool.js" + +const notebook = `${JSON.stringify( + { + cells: [ + { + cell_type: "code", + execution_count: 3, + metadata: {}, + outputs: [{ output_type: "stream", name: "stdout", text: ["hi\n"] }], + source: ["print(1)"] + }, + { cell_type: "markdown", metadata: {}, source: ["# B"] } + ], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 +)}\n` + +const context = (dir: string): ToolContext => + ({ + sessionID: "t", + messageID: "t", + agent: "t", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => { + throw new Error("denied by host") + } + }) as unknown as ToolContext + +const expectDenied = async ( + effect: Effect.Effect +): Promise => { + const exit = await Effect.runPromiseExit(effect) + expect(exit._tag).toBe("Failure") + if (exit._tag !== "Failure") return + const error = Cause.findErrorOption(exit.cause) + expect(error._tag).toBe("Some") + if (error._tag === "Some") { + expect(error.value).toBeInstanceOf(PermissionDeniedError) + } +} + +const operations: Record< + string, + (file: string, services: ReturnType) => Effect.Effect +> = { + editCell: (file, services) => + services.edit.editCell(file, { + cellIndex: 0, + source: "print(2)", + clearOutputs: "never" + }), + insertCell: (file, services) => + services.edit.insertCell(file, "markdown", "# C", 1), + deleteCell: (file, services) => services.edit.deleteCell(file, 0), + moveCell: (file, services) => services.edit.moveCell(file, 0, 1), + clean: (file, services) => services.clean.clean(file, { clearOutputs: true }), + clearCellOutputs: (file, services) => services.output.clearCellOutputs(file, 0), + clearAllOutputs: (file, services) => services.output.clearAllOutputs(file) +} + +const build = (dir: string) => { + const pathSvc = makePathService({ + directory: dir, + worktree: dir, + platform: process.platform + }) + const ctx = context(dir) + const permSvc = makePermissionService(ctx) + const fileSvc = makeNotebookFileService({ worktree: dir }) + return { + edit: makeEditImpl(pathSvc, fileSvc, permSvc), + clean: makeCleanImpl(pathSvc, fileSvc, permSvc), + output: makeOutputImpl(pathSvc, fileSvc, permSvc) + } +} + +describe("a denied edit never reaches the notebook", () => { + for (const [name, operation] of Object.entries(operations)) { + it(`leaves the file byte-identical when ${name} is denied`, async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-deny-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const before = fs.readFileSync(file) + try { + await expectDenied(operation(file, build(dir))) + expect(fs.readFileSync(file).equals(before)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + } +}) diff --git a/test/unit/permission-ordering.test.ts b/test/unit/permission-ordering.test.ts index 0c40c48..b23f9e9 100644 --- a/test/unit/permission-ordering.test.ts +++ b/test/unit/permission-ordering.test.ts @@ -229,7 +229,9 @@ describe("permission ordering", () => { }) ) expect(patterns[0]).toContain(link) - expect(patterns[0]).toContain(real) + // The real target is included in resolved form; on macOS the temp dir is + // spelled through a symlink, so that form differs from the lexical one. + expect(patterns[0]).toContain(fs.realpathSync(real)) } finally { fs.rmSync(dir, { recursive: true, force: true }) } diff --git a/test/unit/persist-outputs.test.ts b/test/unit/persist-outputs.test.ts index e32025c..df1d50e 100644 --- a/test/unit/persist-outputs.test.ts +++ b/test/unit/persist-outputs.test.ts @@ -123,3 +123,34 @@ describe("buildPersistedOutputs", () => { }) }) }) + +describe("buildPersistedOutputs keeps raw MIME bundles", () => { + it("persists multi-mime display_data exactly as the kernel produced it", () => { + const raw = [ + { + output_type: "display_data", + data: { + "text/html": "hi", + "text/plain": "hi", + "image/png": "iVBORw0KGgo=" + }, + metadata: { needs_background: "light" } + }, + { + output_type: "execute_result", + execution_count: 7, + data: { "text/plain": "42", "text/markdown": "**42**" }, + metadata: {} + } + ] + const out = buildPersistedOutputs(makeSummary({ rawOutputs: raw })) + expect(out).toEqual(raw) + }) + + it("falls back to the summary shape when raw outputs are absent", () => { + const out = buildPersistedOutputs( + makeSummary({ stdout: "text", displayData: [{ mime: "image/png", sizeBytes: 9 }] }) + ) + expect(out[0]).toEqual({ output_type: "stream", name: "stdout", text: "text" }) + }) +}) diff --git a/test/unit/plugin-options.test.ts b/test/unit/plugin-options.test.ts index a959249..46cfc71 100644 --- a/test/unit/plugin-options.test.ts +++ b/test/unit/plugin-options.test.ts @@ -6,7 +6,8 @@ import * as path from "node:path" import { makePathService } from "../../src/services/PathService.js" import { parsePluginOptions, resolvePythonPath, type PluginOptions } from "../../src/plugin-options.js" import { resolveToolOptions } from "../../src/tools/_resolveOptions.js" -import { resolveOptionsFromEnv } from "../../src/services/index.js" +import { buildServices, resolveOptionsFromEnv } from "../../src/services/index.js" +import type { ToolContext } from "../../src/tool.js" const ENV_VAR = "OPENCODE_IPYNB_OPTIONS" const ORIGINAL_ENV = process.env[ENV_VAR] @@ -145,7 +146,9 @@ describe("resolvePythonPath", () => { }) const realPython = fs.realpathSync(process.execPath) - const otherReal = fs.realpathSync("/bin/sh") + const otherReal = fs.realpathSync( + process.platform === "win32" ? (process.env.ComSpec ?? "C:\\Windows\\System32\\cmd.exe") : "/bin/sh" + ) it("lets OPENCODE_IPYNB_PYTHON win over the plugin option", () => { process.env.OPENCODE_IPYNB_PYTHON = realPython @@ -229,3 +232,57 @@ describe("PathService with allowOutsideWorktree", () => { }) }) + +const makeServicesContext = (): ToolContext => + ({ + sessionID: "t", + messageID: "t", + agent: "t", + directory: os.tmpdir(), + worktree: os.tmpdir(), + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + }) as unknown as ToolContext + +describe("OPENCODE_IPYNB_OPTIONS failure reporting", () => { + it("reports unparseable JSON through the built services", () => { + setEnv("{ not json") + try { + const services = buildServices(makeServicesContext()) + expect(services.envOptionsError).toBeDefined() + } finally { + setEnv(ORIGINAL_ENV) + } + }) + + it("reports schema-invalid options with the offending field", () => { + setEnv(JSON.stringify({ warmKernel: "yes" })) + try { + const services = buildServices(makeServicesContext()) + expect(services.envOptionsError).toContain("warmKernel") + } finally { + setEnv(ORIGINAL_ENV) + } + }) + + it("reports nothing when the options are valid", () => { + setEnv(JSON.stringify({ warmKernel: true })) + try { + const services = buildServices(makeServicesContext()) + expect(services.envOptionsError).toBeUndefined() + } finally { + setEnv(ORIGINAL_ENV) + } + }) + + it("reports nothing when the variable is unset", () => { + setEnv(undefined) + try { + const services = buildServices(makeServicesContext()) + expect(services.envOptionsError).toBeUndefined() + } finally { + setEnv(ORIGINAL_ENV) + } + }) +}) diff --git a/test/unit/plugin-warnings.test.ts b/test/unit/plugin-warnings.test.ts new file mode 100644 index 0000000..53785a8 --- /dev/null +++ b/test/unit/plugin-warnings.test.ts @@ -0,0 +1,383 @@ +import { afterEach, beforeAll, describe, expect, it, spyOn } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import plugin from "../../src/plugin.js" +import { buildNotebookVirtualDocument } from "../../src/lsp.js" +import { + materializeVirtualDocument +} from "../../src/virtual-materialize.js" + +interface CapturedResult { + content: string + metadata?: Record +} + +interface CapturedHook { + name: string + callback: (event: unknown) => Promise | void +} + +const notebookText = JSON.stringify({ + nbformat: 4, + nbformat_minor: 5, + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "x = 1" + } + ] +}) + +const makeSetup = ( + dir: string, + options: Record, + permission?: (input: { action: string; metadata?: Record }) => Promise +) => { + const hooks: CapturedHook[] = [] + const context = { + location: { directory: dir, project: { directory: dir, canonical: dir } }, + options, + permission: { + assert: async (input: { action: string; metadata?: Record }) => { + await permission?.(input) + } + }, + rpc: { + register: async () => ({ + dispose: async () => {}, + events: { emit: async () => {} } + }) + }, + tool: { + transform: async () => ({ dispose: async () => {} }), + hook: async (name: string, callback: CapturedHook["callback"]) => { + hooks.push({ name, callback }) + return { dispose: async () => {} } + } + } + } + return { context, hooks } +} + +describe("plugin hook reports swallowed failures", () => { + const dirs: string[] = [] + + const makeDir = (): string => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-hook-warn-")) + dirs.push(dir) + return dir + } + + afterEach(() => { + for (const dir of dirs.splice(0)) { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports a sidecar cleanup failure when the plugin unloads", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return + if (process.platform === "win32") return + const dir = makeDir() + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + const subdir = path.join(dir, "sub") + fs.mkdirSync(subdir) + const nested = path.join(subdir, "notebook.ipynb") + fs.writeFileSync(nested, notebookText) + const { context } = makeSetup(dir, { lspDiagnostics: false }) + const cleanup = await plugin.setup(context as never) + const materialized = await materializeVirtualDocument( + buildNotebookVirtualDocument(JSON.parse(notebookText) as never, { + filePath: nested + }), + dir + ) + const target = materialized.path + const mode = fs.statSync(subdir).mode & 0o777 + fs.chmodSync(subdir, 0o500) + try { + const warn = console.warn + const logged: string[] = [] + console.warn = (message?: unknown) => { + logged.push(String(message)) + } + try { + await cleanup?.() + } finally { + console.warn = warn + } + expect(fs.existsSync(target)).toBe(true) + expect(logged.join("\n")).toContain("sidecar-cleanup") + expect(logged.join("\n")).toContain(path.basename(target)) + } finally { + fs.chmodSync(subdir, mode) + fs.rmSync(target, { force: true }) + } + }) + + it("reports a sidecar refresh failure in metadata as well as text", async () => { + const dir = makeDir() + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + const { context, hooks } = makeSetup( + dir, + { lspDiagnostics: false }, + async (input) => { + if (input.metadata?.operation === "materialize-refresh") { + throw new Error("refresh denied") + } + } + ) + await plugin.setup(context as never) + await materializeVirtualDocument( + buildNotebookVirtualDocument(JSON.parse(notebookText) as never, { filePath: file }), + dir + ) + const edited = JSON.parse(notebookText) as { cells: Array<{ source: string }> } + edited.cells[0]!.source = "y = 2" + fs.writeFileSync(file, JSON.stringify(edited)) + const hook = hooks.find((candidate) => candidate.name === "execute.after") + const result: CapturedResult = { content: "Edited", metadata: { changed: true, cellType: "code" } } + await hook?.callback({ + tool: "ipynb_edit", + status: "completed", + input: { filePath: file }, + result + }) + expect(result.content).toContain("Notebook LSP sidecar was not refreshed: refresh denied") + expect(result.metadata?.notebookWarnings).toEqual([ + expect.objectContaining({ source: "sidecar-cleanup", message: "refresh denied" }) + ]) + }) + + it("reports a swallowed diagnostics failure in metadata instead of dropping it", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return + if (process.platform === "win32") return + const dir = makeDir() + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + const { context, hooks } = makeSetup(dir, { lspDiagnostics: true }) + await plugin.setup(context as never) + const mode = fs.statSync(file).mode & 0o777 + fs.chmodSync(file, 0o000) + try { + const hook = hooks.find((candidate) => candidate.name === "execute.after") + const result: CapturedResult = { + content: "Edited", + metadata: { changed: true, cellType: "code" } + } + await hook?.callback({ + tool: "ipynb_edit", + status: "completed", + input: { filePath: file }, + result + }) + expect(result.content).toContain("Notebook diagnostics failed:") + expect(result.metadata?.notebookWarnings).toEqual([ + expect.objectContaining({ + source: "python-probe", + detail: expect.stringContaining("notebook.ipynb") + }) + ]) + } finally { + fs.chmodSync(file, mode) + } + }) + + it("keeps a diagnostics temp-file warning in the result metadata", async () => { + if (process.platform === "win32") return + const dir = makeDir() + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + const pyright = path.join(dir, "fake-pyright") + fs.writeFileSync( + pyright, + "#!/bin/sh\necho '{\"generalDiagnostics\":[]}'\n", + "utf8" + ) + fs.chmodSync(pyright, 0o755) + const { context, hooks } = makeSetup(dir, { + lspDiagnostics: true, + pyrightPath: pyright + }) + await plugin.setup(context as never) + const hook = hooks.find((candidate) => candidate.name === "execute.after") + const result: CapturedResult = { + content: "Edited", + metadata: { changed: true, cellType: "code" } + } + const original = fs.promises.rm + const spy = spyOn(fs.promises, "rm").mockImplementation((( + target: fs.PathLike, + options?: unknown + ) => { + if (String(target).includes("opencode-ipynb-diag-")) { + return Promise.reject( + Object.assign(new Error("busy"), { code: "EBUSY" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + }) as unknown as typeof fs.promises.rm) + try { + await hook?.callback({ + tool: "ipynb_edit", + status: "completed", + input: { filePath: file }, + result + }) + expect(result.metadata?.notebookWarnings).toEqual([ + expect.objectContaining({ + source: "temp-unlink", + detail: expect.stringContaining("opencode-ipynb-diag-") + }) + ]) + } finally { + spy.mockRestore() + } + }) + + it("reports a configured pyright that exists but cannot run", async () => { + if (process.platform === "win32") return + const dir = makeDir() + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + const broken = path.join(dir, "broken-pyright") + fs.writeFileSync(broken, "not executable", "utf8") + fs.chmodSync(broken, 0o644) + const { context, hooks } = makeSetup(dir, { + lspDiagnostics: true, + pyrightPath: broken + }) + await plugin.setup(context as never) + const hook = hooks.find((candidate) => candidate.name === "execute.after") + const result: CapturedResult = { + content: "Edited", + metadata: { changed: true, cellType: "code" } + } + await hook?.callback({ + tool: "ipynb_edit", + status: "completed", + input: { filePath: file }, + result + }) + expect(result.metadata?.notebookWarnings).toEqual([ + expect.objectContaining({ + source: "python-probe", + detail: expect.stringContaining("broken-pyright") + }) + ]) + }) + + it("stays quiet when the default pyright is simply not installed", async () => { + const original = process.env.PATH + const dir = makeDir() + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + process.env.PATH = dir + try { + const { context, hooks } = makeSetup(dir, { + lspDiagnostics: true, + pyrightPath: "pyright" + }) + await plugin.setup(context as never) + const hook = hooks.find((candidate) => candidate.name === "execute.after") + const result: CapturedResult = { + content: "Edited", + metadata: { changed: true, cellType: "code" } + } + await hook?.callback({ + tool: "ipynb_edit", + status: "completed", + input: { filePath: file }, + result + }) + expect(result.metadata?.notebookWarnings).toBeUndefined() + expect(result.content).toBe("Edited") + } finally { + process.env.PATH = original + } + }) + + it("stays quiet when diagnostics succeed", async () => { + const dir = makeDir() + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + const pyright = path.join(dir, "fake-pyright") + fs.writeFileSync(pyright, "#!/bin/sh\necho '{\"generalDiagnostics\":[]}'\n", "utf8") + fs.chmodSync(pyright, 0o755) + const { context, hooks } = makeSetup(dir, { + lspDiagnostics: true, + pyrightPath: pyright + }) + await plugin.setup(context as never) + const hook = hooks.find((candidate) => candidate.name === "execute.after") + const result: CapturedResult = { content: "Edited", metadata: { changed: true, cellType: "code" } } + await hook?.callback({ + tool: "ipynb_edit", + status: "completed", + input: { filePath: file }, + result + }) + expect(result.content).toBe("Edited") + expect(result.metadata?.notebookWarnings).toBeUndefined() + }) +}) + +describe("plugin setup tolerates a missing accumulate helper", () => { + let dir: string + + beforeAll(() => { + dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-hook-setup-")) + }) + + it("still registers the hook when no rpc events are available", async () => { + const file = path.join(dir, "notebook.ipynb") + fs.writeFileSync(file, notebookText) + const hooks: CapturedHook[] = [] + const context = { + location: { directory: dir, project: { directory: dir, canonical: dir } }, + options: { lspDiagnostics: false }, + permission: { assert: async () => {} }, + rpc: { + register: async () => ({ + dispose: async () => {}, + events: { + emit: async () => { + throw new Error("emit failed") + } + } + }) + }, + tool: { + transform: async () => ({ dispose: async () => {} }), + hook: async (name: string, callback: CapturedHook["callback"]) => { + hooks.push({ name, callback }) + return { dispose: async () => {} } + } + } + } + await plugin.setup(context as never) + const hook = hooks.find((candidate) => candidate.name === "execute.after") + const result: CapturedResult = { content: "Edited", metadata: { changed: true } } + await hook?.callback({ + tool: "ipynb_edit", + status: "completed", + input: { filePath: file }, + result + }) + expect(result.content).toBe("Edited") + expect(hooks).toHaveLength(1) + fs.rmSync(dir, { recursive: true, force: true }) + }) +}) diff --git a/test/unit/read-permission-ordering.test.ts b/test/unit/read-permission-ordering.test.ts new file mode 100644 index 0000000..b05647c --- /dev/null +++ b/test/unit/read-permission-ordering.test.ts @@ -0,0 +1,87 @@ +import { describe, expect, it } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { ipynbEditTool } from "../../src/tools/edit.js" +import { ipynbCleanTool } from "../../src/tools/clean.js" +import { ipynbCellInsertTool } from "../../src/tools/cell_insert.js" +import type { ToolContext } from "../../src/tool.js" + +const SECRET = "AWS_SECRET_ACCESS_KEY_HEAD_SUPERSECRET_999" + +const brokenNotebook = `{ "cells": [ ${SECRET} ` + +type Ask = { permission: string; patterns?: string[] } + +const denyingReadContext = (dir: string, asks: Ask[]): ToolContext => + ({ + sessionID: "t", + messageID: "t", + agent: "t", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async (request: Ask) => { + asks.push(request) + if (request.permission === "read") { + throw new Error("read denied by policy") + } + } + }) as unknown as ToolContext + +const outputOf = (result: unknown): string => { + if (typeof result === "string") return result + const record = result as { output?: string; content?: string; message?: string } + return record.output ?? record.content ?? record.message ?? "" +} + +const tools = { + ipynb_edit: (file: string, context: ToolContext) => + ipynbEditTool.execute( + { filePath: file, cellIndex: 0, source: "# B", clearOutputs: "never" }, + context + ), + ipynb_clean: (file: string, context: ToolContext) => + ipynbCleanTool.execute( + { + filePath: file, + clearOutputs: true, + clearExecutionCount: true, + stripWidgetState: true, + stripLargeImages: true, + normalizeSource: true + }, + context + ), + ipynb_cell_insert: (file: string, context: ToolContext) => + ipynbCellInsertTool.execute( + { filePath: file, cellType: "markdown", source: "# C" }, + context + ) +} + +describe("a denied read never discloses notebook bytes", () => { + for (const [name, execute] of Object.entries(tools)) { + it(`${name} asks for read before parsing the notebook`, async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-leak-")) + const file = path.join(dir, "s.ipynb") + fs.writeFileSync(file, brokenNotebook) + const asks: Ask[] = [] + const before = fs.readFileSync(file) + try { + let surfaced = "" + try { + surfaced = outputOf(await execute(file, denyingReadContext(dir, asks))) + } catch (error) { + surfaced = error instanceof Error ? error.message : String(error) + } + expect(surfaced).not.toContain(SECRET) + expect(asks[0]?.permission).toBe("read") + expect(fs.readFileSync(file).equals(before)).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + } +}) diff --git a/test/unit/real-helper.test.ts b/test/unit/real-helper.test.ts index 9af33b1..08f46f2 100644 --- a/test/unit/real-helper.test.ts +++ b/test/unit/real-helper.test.ts @@ -407,13 +407,17 @@ describeIf( start: undefined, end: undefined, kernel: undefined, - timeoutMs: 1_000, + // The budget must cover the kernel's first start (measured ~1.2 s + // inside a container) plus enough of the cell for the child pid to + // be written; a 1 s budget expired during startup on CI, so the + // pid file never appeared and the test proved nothing. + timeoutMs: 5_000, save: false, workingDirectory: undefined, maxOutputChars: 4_000 }) ) - const deadline = Date.now() + 6_000 + const deadline = Date.now() + 20_000 let pid = 0 while (Date.now() < deadline) { if (fs.existsSync(pidFile)) { @@ -423,14 +427,31 @@ describeIf( await new Promise((resolve) => setTimeout(resolve, 50)) } expect(pid).toBeGreaterThan(0) - let alive = true - while (Date.now() < deadline && alive) { + // Signal 0 still succeeds for a zombie, and the descendant's parent may + // be gone without anyone reaping it; read the state so "alive" means + // running rather than merely present in the process table. + const running = (): boolean => { try { process.kill(pid, 0) - await new Promise((resolve) => setTimeout(resolve, 100)) } catch { + return false + } + try { + const stat = fs.readFileSync(`/proc/${pid}/stat`, "utf8") + const at = stat.lastIndexOf(")") + const state = stat.slice(at + 2, at + 3) + return state !== "Z" && state !== "X" + } catch { + return true + } + } + let alive = true + while (Date.now() < deadline && alive) { + if (!running()) { alive = false + break } + await new Promise((resolve) => setTimeout(resolve, 100)) } expect(alive).toBe(false) } finally { diff --git a/test/unit/realpath-cost.test.ts b/test/unit/realpath-cost.test.ts new file mode 100644 index 0000000..d7ea914 --- /dev/null +++ b/test/unit/realpath-cost.test.ts @@ -0,0 +1,55 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { realpathWithRetry } from "../../src/utils/realpath.js" + +const notebook = { cells: [], metadata: {}, nbformat: 4, nbformat_minor: 5 } + +const deepDir = (root: string, depth: number): string => { + let dir = root + for (let index = 0; index < depth; index += 1) dir = path.join(dir, `d${index}`) + fs.mkdirSync(dir, { recursive: true }) + return dir +} + +describe("realpath retry cost", () => { + it("does not spend the retry budget on a path whose parent already exists", async () => { + // The budget below is calibrated on Linux; win32 file APIs have a different + // fixed cost per call, so the same threshold is not meaningful there. + if (process.platform === "win32") return + const root = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-realpath-cost-")) + try { + const dir = deepDir(root, 64) + const missing = path.join(dir, "new.ipynb") + const started = performance.now() + for (let index = 0; index < 20; index += 1) { + await expect(realpathWithRetry(missing)).rejects.toMatchObject({ code: "ENOENT" }) + } + expect(performance.now() - started).toBeLessThan(100) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) + + it("creates a new notebook deep in the worktree well inside a latency budget", async () => { + for (const depth of [8, 64]) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-deep-write-")) + try { + const dir = deepDir(root, depth) + const service = makeNotebookFileService({ worktree: root }) + const started = performance.now() + const exit = await Effect.runPromiseExit( + service.writeAtomic(path.join(dir, "new.ipynb"), notebook as never) + ) + const elapsed = performance.now() - started + expect(exit._tag).toBe("Success") + expect(elapsed).toBeLessThan(100) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + } + }) +}) diff --git a/test/unit/realpath-write-paths.test.ts b/test/unit/realpath-write-paths.test.ts new file mode 100644 index 0000000..a921f3a --- /dev/null +++ b/test/unit/realpath-write-paths.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, it, spyOn } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" + +const notebook = (source: string): string => + `${JSON.stringify( + { + cells: [{ cell_type: "markdown", metadata: {}, source: [source] }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 + }, + null, + 1 + )}\n` + +const transientOnce = (target: string): (() => void) => { + const original = fs.promises.realpath + let failed = false + const spy = spyOn(fs.promises, "realpath") + spy.mockImplementation((( + candidate: fs.PathLike, + ...rest: unknown[] + ) => { + if (!failed && path.resolve(String(candidate)) === path.resolve(target)) { + failed = true + return Promise.reject(Object.assign(new Error("gone"), { code: "ENOENT" })) + } + return (original as unknown as (...args: never[]) => Promise)( + (candidate as never), + ...(rest as never[]) + ) + }) as unknown as typeof fs.promises.realpath) + return () => spy.mockRestore() +} + +describe("transient realpath in the write and lock paths", () => { + it("writes through a symlink even when realpath fails once", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-symlink-retry-")) + const real = path.join(dir, "real.ipynb") + const alias = path.join(dir, "alias.ipynb") + fs.writeFileSync(real, notebook("# A")) + fs.symlinkSync(real, alias) + const restore = transientOnce(alias) + try { + const svc = makeNotebookFileService({ worktree: dir }) + const read = await Effect.runPromise(svc.readWithText(alias)) + const exit = await Effect.runPromiseExit( + svc.writeAtomic(alias, read.notebook as never, { + format: read.format, + previousText: read.text + }) + ) + expect(exit._tag).toBe("Success") + expect(fs.lstatSync(alias).isSymbolicLink()).toBe(true) + expect(fs.readFileSync(real, "utf8")).toContain("# A") + } finally { + restore() + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("keys the lock by real path even when realpath fails once", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-lock-retry-")) + const real = path.join(dir, "real.ipynb") + const alias = path.join(dir, "alias.ipynb") + fs.writeFileSync(real, notebook("# A")) + fs.symlinkSync(real, alias) + const restore = transientOnce(alias) + try { + const svc = makeNotebookFileService({ worktree: dir }) + let active = 0 + let maxActive = 0 + const hold = (): Promise => + svc + .withFileLock( + alias, + Effect.promise(async () => { + active += 1 + maxActive = Math.max(maxActive, active) + await new Promise((resolve) => setTimeout(resolve, 40)) + active -= 1 + }) + ) + .pipe(Effect.runPromise) + const holdReal = (): Promise => + svc + .withFileLock( + real, + Effect.promise(async () => { + active += 1 + maxActive = Math.max(maxActive, active) + await new Promise((resolve) => setTimeout(resolve, 40)) + active -= 1 + }) + ) + .pipe(Effect.runPromise) + await Promise.all([hold(), holdReal()]) + expect(maxActive).toBe(1) + } finally { + restore() + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/repro.test.ts b/test/unit/repro.test.ts index 60a0558..67f80a4 100644 --- a/test/unit/repro.test.ts +++ b/test/unit/repro.test.ts @@ -64,6 +64,7 @@ const rawCell = (source: string): RawCellRaw => ({ const buildNotebook = (cells: ReadonlyArray): NotebookRaw => ({ nbformat: 4, + nbformat_minor: 5, metadata: { kernelspec: { display_name: "Python 3", name: "python3", language: "python" }, language_info: { name: "python" } diff --git a/test/unit/run-save-merge.test.ts b/test/unit/run-save-merge.test.ts new file mode 100644 index 0000000..1ffae11 --- /dev/null +++ b/test/unit/run-save-merge.test.ts @@ -0,0 +1,91 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import { + mergeExecutedOutputs, + type MergeShapeInputs +} from "../../src/services/NotebookExecutionService.js" +import type { CellRaw, CodeCellRaw } from "../../src/domain/cell.js" +import type { CellExecutionSummary } from "../../src/domain/execution.js" + +const codeCell = (): CellRaw => + ({ + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "x = 1" + }) as CellRaw + +const summaryAt = ( + cellIndex: number, + stdout: string +): CellExecutionSummary => + ({ + cellIndex, + status: "ok", + stdout + }) as CellExecutionSummary + +const shapes = (fallback: MergeShapeInputs["fallback"] = "strings"): MergeShapeInputs => ({ + fallback, + beforeShapes: undefined, + beforeValueShapes: undefined +}) + +describe("mergeExecutedOutputs", () => { + it("keeps the first summary when the runner reports duplicates", async () => { + const exit = await Effect.runPromiseExit( + mergeExecutedOutputs("n.ipynb", [codeCell()], [0], [ + summaryAt(0, "first"), + summaryAt(0, "second") + ], shapes()) + ) + if (exit._tag !== "Success") throw new Error("expected a success") + const merged: Map = exit.value + expect(merged.size).toBe(1) + const outputs = [...merged.get(0)!.outputs] + expect(outputs[0]).toMatchObject({ name: "stdout", text: "first" }) + }) + + it("skips non-code cells and cells without a summary", async () => { + const cells: CellRaw[] = [ + codeCell(), + { cell_type: "markdown", metadata: {}, source: "text" } as unknown as CellRaw + ] + const exit = await Effect.runPromiseExit( + mergeExecutedOutputs("n.ipynb", cells, [0, 1], [summaryAt(0, "ok")], shapes()) + ) + if (exit._tag !== "Success") throw new Error("expected a success") + expect(exit.value.size).toBe(1) + expect([...exit.value.keys()]).toEqual([0]) + }) + + it("fails with the reported index when the runner goes out of bounds", async () => { + const exit = await Effect.runPromiseExit( + mergeExecutedOutputs("n.ipynb", [codeCell()], [3], [], shapes()) + ) + expect(exit._tag).toBe("Failure") + }) + + it("scales linearly with executed cells", async () => { + const cells: CellRaw[] = [] + const executedCells: number[] = [] + const summaries: CellExecutionSummary[] = [] + for (let index = 0; index < 32_000; index += 1) { + cells.push(codeCell()) + executedCells.push(index) + summaries.push(summaryAt(index, `out ${index}`)) + } + const started = Date.now() + const exit = await Effect.runPromiseExit( + mergeExecutedOutputs("n.ipynb", cells, executedCells, summaries, shapes()) + ) + const elapsed = Date.now() - started + if (exit._tag !== "Success") throw new Error("expected a success") + expect(exit.value.size).toBe(32_000) + expect([...exit.value.get(31_999)!.outputs][0]).toMatchObject({ + text: "out 31999" + }) + expect(elapsed).toBeLessThan(300) + }) +}) diff --git a/test/unit/shell-guard.test.ts b/test/unit/shell-guard.test.ts new file mode 100644 index 0000000..5ce644f --- /dev/null +++ b/test/unit/shell-guard.test.ts @@ -0,0 +1,82 @@ +import { describe, expect, it } from "bun:test" +import { + diagnosticsSkipReason, + hasShellMetacharacters, + shellCommandRefusal, + ShellCommandError +} from "../../src/notebook-diagnostics.js" + +describe("shell metacharacter guard", () => { + it("rejects every character a cmd shell would reinterpret", () => { + const rejected = [ + "C:\\dir%PATH%\\pyright.cmd", + "C:\\tom & jerry\\pyright.cmd", + "C:\\a|b\\pyright.cmd", + "C:\\ab\\pyright.cmd", + "C:\\a^b\\pyright.cmd", + "C:\\a\"b\\pyright.cmd", + "C:\\a\rb\\pyright.cmd", + "C:\\a\nb\\pyright.cmd" + ] + for (const value of rejected) { + expect(hasShellMetacharacters(value)).toBe(true) + } + }) + + it("accepts ordinary command paths and arguments", () => { + const accepted = [ + "pyright", + "pyright.cmd", + "C:\\Program Files\\pyright\\pyright.cmd", + "/usr/local/bin/pyright", + "--outputjson", + "--pythonpath", + "/home/user/notebooks/dir with spaces/n.py", + "/home/user/ünicode-𝄞/n.py", + "C:\\dir(parens)\\pyright.cmd" + ] + for (const value of accepted) { + expect(hasShellMetacharacters(value)).toBe(false) + } + }) + + it("refuses only when the shell path is active", () => { + const dirty = "C:\\dir%VAR%\\pyright.cmd" + expect(shellCommandRefusal(dirty, [], false)).toBeUndefined() + expect(shellCommandRefusal(dirty, [], true)).toBeInstanceOf(ShellCommandError) + expect(shellCommandRefusal("pyright.cmd", ["--outputjson", "C:\\a&b\\n.py"], true)).toBeInstanceOf( + ShellCommandError + ) + expect( + shellCommandRefusal("C:\\Program Files\\pyright\\pyright.cmd", ["--outputjson", "C:\\clean\\n.py"], true) + ).toBeUndefined() + }) + + it("names the offending part of the command line", () => { + const command = shellCommandRefusal("C:\\a%b\\pyright.cmd", [], true) + expect(command?.message).toContain("%") + expect(command?.message).toContain("command") + const arg = shellCommandRefusal("pyright.cmd", ["--outputjson", "C:\\a|b\\n.py"], true) + expect(arg?.message).toContain("C:") + expect(arg?.message).toContain("|") + expect(arg?.message).toContain("argument") + }) + + it("classifies a refused command as unsafe-shell-command", () => { + expect(diagnosticsSkipReason(new ShellCommandError("refused"))).toBe("unsafe-shell-command") + expect(diagnosticsSkipReason(Object.assign(new Error("spawn missing"), { code: "ENOENT" }))).toBe( + "pyright-not-found" + ) + expect(diagnosticsSkipReason(Object.assign(new Error("spawn denied"), { code: "EACCES" }))).toBe( + "pyright-not-executable" + ) + expect(diagnosticsSkipReason(Object.assign(new Error("spawn denied"), { code: "EPERM" }))).toBe( + "pyright-not-executable" + ) + expect(diagnosticsSkipReason(Object.assign(new Error("spawn denied"), { code: "EROFS" }))).toBe( + "pyright-not-executable" + ) + expect(diagnosticsSkipReason(new Error("anything else"))).toBe("invalid-output") + }) +}) diff --git a/test/unit/silence-allowlist.test.ts b/test/unit/silence-allowlist.test.ts new file mode 100644 index 0000000..47f0b14 --- /dev/null +++ b/test/unit/silence-allowlist.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from "bun:test" +import * as fs from "node:fs" +import * as path from "node:path" + +const srcRoot = path.join(import.meta.dir, "..", "..", "src") + +const silentCatch = + /\.catch\(\s*(?:\([^)]*\)|[A-Za-z_$][\w$]*)\s*=>\s*(?:\{\s*\}|undefined|false|null|\[\]|""|[A-Za-z_$][\w$]*)\s*\)|\bcatch\s*(?:\([^)]*\))?\s*\{\s*\}/g + +const allowlist = new Map([ + ["services/KernelManager.ts|.catch(() => {})", 1], + ["notebook-diagnostics.ts|.catch(() => {})", 1], + ["plugin-v2.ts|.catch(() => {})", 1], + ["services/PythonService.ts|catch { }", 3], + ["notebook-diagnostics.ts|catch { }", 2], + ["virtual-materialize.ts|catch { }", 1], + ["plugin-options.ts|catch { }", 1], + ["services/revision.ts|.catch(() => filePath)", 1], + ["services/NotebookFileService.ts|.catch(() => worktree)", 2], + ["services/NotebookFileService.ts|.catch(() => resolved)", 1], + ["tools/kernel.ts|.catch(() => abs)", 1] +]) + +const listFiles = (dir: string): string[] => + fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => { + const full = path.join(dir, entry.name) + if (entry.isDirectory()) return listFiles(full) + return entry.name.endsWith(".ts") ? [full] : [] + }) + +const normalize = (match: string): string => match.replace(/\s+/g, " ").trim() + +describe("silent failure allowlist", () => { + it("keeps every swallowed failure either reported or on the allowlist", () => { + const remaining = new Map(allowlist) + const offenders: string[] = [] + for (const file of listFiles(srcRoot)) { + const rel = path.relative(srcRoot, file).split(path.sep).join("/") + const content = fs.readFileSync(file, "utf8") + for (const match of content.matchAll(silentCatch)) { + const key = `${rel}|${normalize(match[0])}` + const left = remaining.get(key) + if (left === undefined) { + offenders.push(`unlisted silent failure at ${rel} near offset ${match.index ?? 0}: ${normalize(match[0])}`) + continue + } + if (left === 1) remaining.delete(key) + else remaining.set(key, left - 1) + } + } + for (const key of remaining.keys()) { + offenders.push(`stale allowlist entry: ${key}`) + } + expect(offenders).toEqual([]) + }) +}) diff --git a/test/unit/swallowed-failures.test.ts b/test/unit/swallowed-failures.test.ts new file mode 100644 index 0000000..8c56ec9 --- /dev/null +++ b/test/unit/swallowed-failures.test.ts @@ -0,0 +1,900 @@ +import { afterEach, describe, expect, it, spyOn } from "bun:test" +import { Cause, Effect } from "effect" +import * as fs from "node:fs" +import * as fsp from "node:fs/promises" +import * as os from "node:os" +import * as path from "node:path" +import { makeKernelManager } from "../../src/services/KernelManager.js" +import type { KernelManagerShape } from "../../src/services/KernelManager.js" +import { makeExecutionImpl } from "../../src/services/NotebookExecutionService.js" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { makePathService } from "../../src/services/PathService.js" +import { makePermissionService } from "../../src/services/PermissionService.js" +import { makePythonService, type PythonServiceShape } from "../../src/services/PythonService.js" +import { makeWarningSink } from "../../src/utils/warnings.js" +import { samePhysicalPath } from "../helpers.js" +import { NotebookValidationError } from "../../src/domain/errors.js" +import { DEFAULT_NOTEBOOK_FORMAT } from "../../src/utils/json.js" +import type { NotebookRaw } from "../../src/domain/notebook.js" +import { + cleanupVirtualDocuments, + hasMaterializedDocument, + materializeVirtualDocument +} from "../../src/virtual-materialize.js" +import { buildNotebookVirtualDocument } from "../../src/lsp.js" +import { + diagnoseNotebook, + diagnosticTempPath +} from "../../src/notebook-diagnostics.js" +import type { ToolContext } from "../../src/tool.js" + +const notebook = { + nbformat: 4, + nbformat_minor: 5, + metadata: { + kernelspec: { display_name: "Python 3", language: "python", name: "python3" }, + language_info: { name: "python", file_extension: ".py" } + }, + cells: [ + { + cell_type: "code", + execution_count: null, + metadata: {}, + outputs: [], + source: "x = 1" + } + ] +} + +const makeContext = (dir: string): ToolContext => + ({ + sessionID: "t", + messageID: "t", + agent: "t", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {} + }) as unknown as ToolContext + +const writeScript = (dir: string, name: string, body: string): string => { + const file = path.join(dir, name) + fs.writeFileSync(file, body, "utf8") + fs.chmodSync(file, 0o755) + return file +} + +const shellHelper = (dir: string, preamble: string): string => + writeScript( + dir, + "helper.sh", + `#!/bin/sh +${preamble} +IFS= read -r init +printf '{"ready": true, "pid": %s, "kernelPid": %s}\\n' "$$" "$$" +IFS= read -r req +id=$(printf '%s' "$req" | sed -n 's/.*"id"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p') +nonce=$(printf '%s' "$req" | sed -n 's/.*"nonce"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\\1/p') +printf '{"id": %s, "nonce": "%s", "success": true, "executedCells": [], "durationMs": 1, "outputs": []}\\n' "$id" "$nonce" +` + ) + +const fakeKernel = (): KernelManagerShape => + ({ + execute: () => + Effect.succeed({ + success: true, + executedCells: [0], + durationMs: 1, + outputs: [{ cellIndex: 0, status: "ok" as const, stdout: "ok\n" }] + }) + }) as unknown as KernelManagerShape + +const fakePython = (): PythonServiceShape => + ({ + probe: () => + Effect.succeed({ + pythonPath: "/usr/bin/python3", + version: "3", + executable: "python3", + from: "options" as const + }), + findHelper: () => Effect.succeed("/tmp/ipynb_runner.py"), + checkDependencies: () => Effect.succeed([]), + candidates: () => Effect.succeed([]), + checkImport: () => Effect.succeed({ name: "x", available: true, detail: "ok" }), + doctor: () => Effect.succeed({} as never) + }) as unknown as PythonServiceShape + +describe("swallowed failures stay observable", () => { + afterEach(() => { + if (restore.length > 0) { + for (const undo of restore.splice(0)) undo() + } + }) + const restore: Array<() => void> = [] + + it("records a kernel warning for a non-protocol stdout line", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-kernel-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const helper = shellHelper(dir, `printf 'this is not json\\n'`) + const sink = makeWarningSink() + const mgr = makeKernelManager({ + pythonPath: "/bin/sh", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 10_000, + warningSink: sink + }) + try { + const response = await Effect.runPromise( + mgr.execute(file, { + filePath: file, + mode: "all", + timeoutMs: 10_000, + save: false, + maxOutputChars: 4_000 + }) + ) + expect(response.success).toBe(true) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("python-probe") + expect(warnings[0]?.detail).toContain("this is not json") + expect(mgr.list()[0]?.warnings).toEqual(warnings) + } finally { + await Effect.runPromise(mgr.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("routes a kernel warning to the sink of the in-flight request", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-kernel-request-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const helper = writeScript( + dir, + "late-helper.sh", + `#!/bin/sh +IFS= read -r init +printf '{"ready": true, "pid": 1, "kernelPid": 2}\\n' +IFS= read -r req +printf 'not json either\\n' +id=$(printf '%s' "$req" | sed -n 's/.*"id"[[:space:]]*:[[:space:]]*\\([0-9][0-9]*\\).*/\\1/p') +nonce=$(printf '%s' "$req" | sed -n 's/.*"nonce"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\\1/p') +printf '{"id": %s, "nonce": "%s", "success": true, "executedCells": [], "durationMs": 1, "outputs": []}\\n' "$id" "$nonce" +` + ) + const mgr = makeKernelManager({ + pythonPath: "/bin/sh", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 10_000 + }) + const sink = makeWarningSink() + try { + await Effect.runPromise( + mgr.execute( + file, + { + filePath: file, + mode: "all", + timeoutMs: 10_000, + save: false, + maxOutputChars: 4_000 + }, + undefined, + { warningSink: sink } + ) + ) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("python-probe") + expect(warnings[0]?.detail).toContain("not json either") + } finally { + await Effect.runPromise(mgr.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("records a non-object JSON line from the helper", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-kernel-json-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const helper = shellHelper(dir, `printf '42\\n'`) + const sink = makeWarningSink() + const mgr = makeKernelManager({ + pythonPath: "/bin/sh", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 10_000, + warningSink: sink + }) + try { + await Effect.runPromise( + mgr.execute(file, { + filePath: file, + mode: "all", + timeoutMs: 10_000, + save: false, + maxOutputChars: 4_000 + }) + ) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("python-probe") + expect(warnings[0]?.message).toContain("non-object JSON") + } finally { + await Effect.runPromise(mgr.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("does not warn for a healthy kernel request or a clean shutdown", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-quiet-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const helper = shellHelper(dir, "") + const sink = makeWarningSink() + const mgr = makeKernelManager({ + pythonPath: "/bin/sh", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 10_000, + warningSink: sink + }) + try { + await Effect.runPromise( + mgr.execute(file, { + filePath: file, + mode: "all", + timeoutMs: 10_000, + save: false, + maxOutputChars: 4_000 + }) + ) + await Effect.runPromise(mgr.disposeAll()) + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("keys a kernel correctly when the notebook is missing without warning", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-kernel-missing-")) + const file = path.join(dir, "missing.ipynb") + const helper = shellHelper(dir, "") + const sink = makeWarningSink() + const mgr = makeKernelManager({ + pythonPath: "/bin/sh", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 10_000, + warningSink: sink + }) + try { + const response = await Effect.runPromise( + mgr.execute(file, { + filePath: file, + mode: "all", + timeoutMs: 10_000, + save: false, + maxOutputChars: 4_000 + }) + ) + expect(response.success).toBe(true) + expect(mgr.isRunning(file)).toBe(true) + expect(sink.drain()).toEqual([]) + } finally { + await Effect.runPromise(mgr.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("records the realpath fallback used to key a kernel", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-realpath-")) + const file = path.join(dir, "missing.ipynb") + const helper = shellHelper(dir, "") + const sink = makeWarningSink() + const mgr = makeKernelManager({ + pythonPath: "/bin/sh", + helperPath: helper, + workingDirectory: dir, + defaultTimeoutMs: 10_000, + warningSink: sink + }) + const original = fs.promises.realpath + const spy = spyOn(fs.promises, "realpath").mockImplementation((( + target: fs.PathLike, + ...rest: unknown[] + ) => { + if (path.resolve(String(target)) === path.resolve(file)) { + return Promise.reject( + Object.assign(new Error("cannot resolve notebook"), { code: "EACCES" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + ...rest + ) + }) as unknown as typeof fs.promises.realpath) + restore.push(() => spy.mockRestore()) + try { + await Effect.runPromise( + mgr.execute(file, { + filePath: file, + mode: "all", + timeoutMs: 10_000, + save: false, + maxOutputChars: 4_000 + }) + ) + const warnings = sink.drain() + expect(warnings.length).toBeGreaterThan(0) + expect(warnings.every((warning) => warning.source === "path-resolution")).toBe(true) + expect(warnings[0]?.detail).toContain("missing.ipynb") + } finally { + await Effect.runPromise(mgr.disposeAll()) + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports a path-resolution fallback in the execution result", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-exec-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const original = fs.promises.realpath + const spy = spyOn(fs.promises, "realpath").mockImplementation((( + target: fs.PathLike, + ...rest: unknown[] + ) => { + if (path.resolve(String(target)) === path.resolve(file)) { + return Promise.reject( + Object.assign(new Error("cannot resolve notebook"), { code: "EACCES" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + ...rest + ) + }) as unknown as typeof fs.promises.realpath) + restore.push(() => spy.mockRestore()) + const exec = makeExecutionImpl( + makePathService({ directory: dir, worktree: dir, platform: process.platform }), + makeNotebookFileService(), + makePermissionService(makeContext(dir)), + fakePython(), + { kernelManager: fakeKernel(), warmKernel: true, defaultTimeoutMs: 30_000 } + ) + try { + const result = await Effect.runPromise( + exec.execute(file, { + mode: "all", + cellIndex: undefined, + start: undefined, + end: undefined, + kernel: undefined, + timeoutMs: 30_000, + save: false, + workingDirectory: undefined, + maxOutputChars: 4_000 + }) + ) + expect(result.warnings?.map((warning) => warning.source)).toEqual([ + "path-resolution" + ]) + expect(result.warnings?.[0]?.detail).toContain("n.ipynb") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("records a warning when the write-path realpath probe fails", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-write-realpath-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const original = fsp.realpath + const spy = spyOn(fsp, "realpath").mockImplementation((( + target: fs.PathLike, + ...rest: unknown[] + ) => { + if (path.resolve(String(target)) === path.resolve(file)) { + return Promise.reject( + Object.assign(new Error("cannot resolve notebook"), { code: "EACCES" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + ...rest + ) + }) as unknown as typeof fsp.realpath) + restore.push(() => spy.mockRestore()) + const sink = makeWarningSink() + const svc = makeNotebookFileService({ worktree: dir, warningSink: sink }) + try { + await Effect.runPromise( + svc.writeAtomic(file, { + ...notebook, + cells: [{ ...notebook.cells[0]!, source: "x = 2" }] + } as unknown as NotebookRaw) + ) + const warnings = sink.drain() + const pathWarnings = warnings.filter( + (warning) => warning.source === "path-resolution" + ) + expect(pathWarnings.length).toBeGreaterThanOrEqual(1) + expect(pathWarnings.some((warning) => (warning.detail ?? "").includes("n.ipynb"))).toBe(true) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("announces a fallback rewrite through the warning sink", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-fallback-")) + const file = path.join(dir, "n.ipynb") + const broken = `{ not json` + fs.writeFileSync(file, broken) + const sink = makeWarningSink() + const svc = makeNotebookFileService({ worktree: dir, warningSink: sink }) + try { + const outcome = await Effect.runPromise( + svc.writeAtomic(file, { + ...notebook, + cells: [{ ...notebook.cells[0]!, source: "x = 2" }] + } as unknown as NotebookRaw, { + format: DEFAULT_NOTEBOOK_FORMAT, + previousText: broken + }) + ) + expect(outcome.mode).toBe("fallback") + expect(outcome.reason).toBe("parse-failed") + expect(JSON.parse(fs.readFileSync(file, "utf8"))).toBeDefined() + const warnings = sink.drain() + expect(warnings.length).toBe(1) + expect(warnings[0]?.source).toBe("json-patch") + expect(warnings[0]?.message).toContain("rewritten from scratch") + expect(warnings[0]?.message).toContain("parse-failed") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("records a warning when the write-path stat probe fails", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-write-stat-")) + const file = path.join(dir, "n.ipynb") + const original = fsp.stat + const spy = spyOn(fsp, "stat").mockImplementation((( + target: fs.PathLike, + ...rest: unknown[] + ) => { + if (path.resolve(String(target)) === path.resolve(file)) { + return Promise.reject(Object.assign(new Error("denied"), { code: "EACCES" })) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + ...rest + ) + }) as unknown as typeof fsp.stat) + restore.push(() => spy.mockRestore()) + const sink = makeWarningSink() + const svc = makeNotebookFileService({ worktree: dir, warningSink: sink }) + try { + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, notebook as unknown as NotebookRaw) + ) + expect(exit._tag).toBe("Failure") + const error = exit._tag === "Failure" ? Cause.findErrorOption(exit.cause) : undefined + const failure = error?._tag === "Some" ? error.value : undefined + expect(failure).toBeInstanceOf(NotebookValidationError) + expect((failure as { message?: string }).message).toContain("could not be read") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("forwards kernel warnings to a caller-supplied sink", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-exec-sink-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const kernelSink = makeWarningSink() + const kernel = { + execute: (_path: string, _request: unknown, _runtime: unknown, options?: { + readonly warningSink?: { readonly add: (warning: unknown) => void } + }) => + Effect.sync(() => { + options?.warningSink?.add({ + source: "python-probe", + message: "helper emitted noise", + detail: "ignored line" + }) + return { + success: true, + executedCells: [0], + durationMs: 1, + outputs: [{ cellIndex: 0, status: "ok" as const, stdout: "ok\n" }] + } + }) + } as unknown as KernelManagerShape + const exec = makeExecutionImpl( + makePathService({ directory: dir, worktree: dir, platform: process.platform }), + makeNotebookFileService(), + makePermissionService(makeContext(dir)), + fakePython(), + { kernelManager: kernel, warmKernel: true, defaultTimeoutMs: 30_000 } + ) + try { + const result = await Effect.runPromise( + exec.execute( + file, + { + mode: "all", + cellIndex: undefined, + start: undefined, + end: undefined, + kernel: undefined, + timeoutMs: 30_000, + save: false, + workingDirectory: undefined, + maxOutputChars: 4_000 + }, + { warningSink: kernelSink } + ) + ) + expect(result.warnings).toEqual([ + { source: "python-probe", message: "helper emitted noise", detail: "ignored line" } + ]) + expect(kernelSink.drain()).toEqual([ + { source: "python-probe", message: "helper emitted noise", detail: "ignored line" } + ]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("returns no warnings for a healthy execution", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-exec-clean-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const exec = makeExecutionImpl( + makePathService({ directory: dir, worktree: dir, platform: process.platform }), + makeNotebookFileService(), + makePermissionService(makeContext(dir)), + fakePython(), + { kernelManager: fakeKernel(), warmKernel: true, defaultTimeoutMs: 30_000 } + ) + try { + const result = await Effect.runPromise( + exec.execute(file, { + mode: "all", + cellIndex: undefined, + start: undefined, + end: undefined, + kernel: undefined, + timeoutMs: 30_000, + save: false, + workingDirectory: undefined, + maxOutputChars: 4_000 + }) + ) + expect(result.warnings).toBeUndefined() + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("records why the configured interpreter failed to probe", async () => { + const sink = makeWarningSink() + const svc = makePythonService({ + pythonPath: "/nonexistent/ipynb-python-xyz", + preferUv: false, + helperRelativePath: "python/ipynb_runner.py" + }) + const probe = await Effect.runPromise(svc.probe({ warningSink: sink })) + expect(probe.from).toBe("none") + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("python-probe") + expect(warnings[0]?.detail).toContain("ipynb-python-xyz") + }) + + it("records a relative configured interpreter that is never probed", async () => { + const sink = makeWarningSink() + const svc = makePythonService({ + pythonPath: "some/relative/python", + preferUv: false, + helperRelativePath: "python/ipynb_runner.py" + }) + const probe = await Effect.runPromise(svc.probe({ warningSink: sink })) + expect(probe.from).toBe("none") + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("python-probe") + expect(warnings[0]?.detail).toContain("some/relative/python") + }) + + it("stays quiet when an unconfigured PATH interpreter is missing", async () => { + const sink = makeWarningSink() + const svc = makePythonService({ + pythonPath: undefined, + preferUv: false, + helperRelativePath: "python/ipynb_runner.py" + }) + await Effect.runPromise(svc.probe({ warningSink: sink })) + expect(sink.drain()).toEqual([]) + }) + + it("records a leftover sidecar temp file when the write fails", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-sidecar-tmp-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const document = buildNotebookVirtualDocument(notebook, { filePath: file }) + const originalRm = fs.promises.rm + const rmSpy = spyOn(fs.promises, "rm").mockImplementation((( + target: fs.PathLike, + options?: unknown + ) => { + if (String(target).includes("opencode-ipynb-lsp-")) { + return Promise.reject( + Object.assign(new Error("busy"), { code: "EBUSY" }) + ) + } + return (originalRm as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + }) as unknown as typeof fs.promises.rm) + restore.push(() => rmSpy.mockRestore()) + const originalRename = fs.promises.rename + const renameSpy = spyOn(fs.promises, "rename").mockImplementation((( + from: fs.PathLike, + to: fs.PathLike + ) => { + if (String(to).includes("opencode-ipynb-lsp-")) { + return Promise.reject( + Object.assign(new Error("rename refused"), { code: "EPERM" }) + ) + } + return originalRename(from, to) + }) as unknown as typeof fs.promises.rename) + restore.push(() => renameSpy.mockRestore()) + const sink = makeWarningSink() + try { + let message = "" + try { + await materializeVirtualDocument(document, dir, { warningSink: sink }) + } catch (error) { + message = error instanceof Error ? error.message : String(error) + } + expect(message).toContain("rename refused") + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("temp-unlink") + expect(warnings[0]?.detail).toContain(".tmp") + const leftovers = fs.readdirSync(dir).filter((entry) => entry.endsWith(".tmp")) + expect(leftovers).toHaveLength(1) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("records a failed sidecar removal instead of dropping it", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-sidecar-clean-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const document = buildNotebookVirtualDocument(notebook, { filePath: file }) + const materialized = await materializeVirtualDocument(document, dir) + const original = fs.promises.rm + const spy = spyOn(fs.promises, "rm").mockImplementation((( + target: fs.PathLike, + options?: unknown + ) => { + // cleanup resolves the sidecar path, which on macOS is spelled through + // the /tmp symlink and on Windows through an 8.3 short name; match the + // physical file instead of the lexical spelling. + if (samePhysicalPath(String(target), materialized.path)) { + return Promise.reject( + Object.assign(new Error("busy"), { code: "EBUSY" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + }) as unknown as typeof fs.promises.rm) + restore.push(() => spy.mockRestore()) + const sink = makeWarningSink() + try { + await cleanupVirtualDocuments(dir, { warningSink: sink }) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("sidecar-cleanup") + expect(warnings[0]?.detail).toContain("opencode-ipynb-lsp-") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("records an unreadable legacy sidecar directory", async () => { + if (typeof process.getuid === "function" && process.getuid() === 0) return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-legacy-")) + const legacy = path.join(dir, ".opencode", "ipynb-lsp") + fs.mkdirSync(legacy, { recursive: true }) + const original = fs.promises.readdir + const spy = spyOn(fs.promises, "readdir").mockImplementation((( + target: fs.PathLike, + options?: unknown + ) => { + // Same as above: the legacy directory is listed through its resolved + // spelling, so match the physical directory. + if (samePhysicalPath(String(target), legacy)) { + return Promise.reject( + Object.assign(new Error("denied"), { code: "EACCES" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + }) as unknown as typeof fs.promises.readdir) + restore.push(() => spy.mockRestore()) + const sink = makeWarningSink() + try { + await cleanupVirtualDocuments(dir, { warningSink: sink }) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("sidecar-cleanup") + expect(warnings[0]?.detail).toContain(".opencode") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports a diagnostics temp file that could not be removed", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-diag-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const pyright = writeScript(dir, "fake-pyright", '#!/bin/sh\necho \'{"generalDiagnostics":[]}\'\n') + const temp = diagnosticTempPath(file) + const original = fs.promises.rm + const spy = spyOn(fs.promises, "rm").mockImplementation((( + target: fs.PathLike, + options?: unknown + ) => { + if (path.resolve(String(target)) === path.resolve(temp)) { + return Promise.reject( + Object.assign(new Error("busy"), { code: "EBUSY" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + }) as unknown as typeof fs.promises.rm) + restore.push(() => spy.mockRestore()) + try { + const result = await diagnoseNotebook({ + filePath: file, + document: buildNotebookVirtualDocument(notebook, { filePath: file }), + pyrightPath: pyright, + timeoutMs: 10_000 + }) + expect(result.skipped).toBeUndefined() + expect(result.warnings).toHaveLength(1) + expect(result.warnings?.[0]?.source).toBe("temp-unlink") + expect(result.warnings?.[0]?.detail).toContain(path.basename(temp)) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports a diagnostics directory it could not resolve", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-diag-dir-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const pyright = writeScript(dir, "fake-pyright", '#!/bin/sh\necho \'{"generalDiagnostics":[]}\'\n') + const original = fs.realpathSync + const spy = spyOn(fs, "realpathSync").mockImplementation(((target: fs.PathLike) => { + if (path.resolve(String(target)) === path.resolve(file)) { + throw Object.assign(new Error("cannot resolve"), { code: "EACCES" }) + } + return original(target) + }) as unknown as typeof fs.realpathSync) + restore.push(() => spy.mockRestore()) + try { + const result = await diagnoseNotebook({ + filePath: file, + document: buildNotebookVirtualDocument(notebook, { filePath: file }), + pyrightPath: pyright, + timeoutMs: 10_000 + }) + const warnings = result.warnings ?? [] + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("path-resolution") + expect(warnings[0]?.detail).toContain("n.ipynb") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("reports a sidecar it could not inspect instead of assuming none", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-has-sidecar-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const document = buildNotebookVirtualDocument(notebook, { filePath: file }) + const materialized = await materializeVirtualDocument(document, dir) + const original = fs.promises.lstat + const spy = spyOn(fs.promises, "lstat").mockImplementation((( + target: fs.PathLike, + options?: unknown + ) => { + if (path.resolve(String(target)) === path.resolve(materialized.path)) { + return Promise.reject( + Object.assign(new Error("denied"), { code: "EACCES" }) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + }) as unknown as typeof fs.promises.lstat) + restore.push(() => spy.mockRestore()) + const sink = makeWarningSink() + try { + const exists = await hasMaterializedDocument(dir, file, { warningSink: sink }) + expect(exists).toBe(false) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("sidecar-cleanup") + expect(warnings[0]?.detail).toContain("opencode-ipynb-lsp-") + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("stays quiet when a notebook was never materialized", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-no-sidecar-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const sink = makeWarningSink() + try { + const exists = await hasMaterializedDocument(dir, file, { warningSink: sink }) + expect(exists).toBe(false) + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("returns no diagnostics warnings for a clean run", async () => { + if (process.platform === "win32") return + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-warn-diag-clean-")) + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, JSON.stringify(notebook)) + const pyright = writeScript(dir, "fake-pyright", '#!/bin/sh\necho \'{"generalDiagnostics":[]}\'\n') + try { + const result = await diagnoseNotebook({ + filePath: file, + document: buildNotebookVirtualDocument(notebook, { filePath: file }), + pyrightPath: pyright, + timeoutMs: 10_000 + }) + expect(result.skipped).toBeUndefined() + expect(result.warnings).toBeUndefined() + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) +}) diff --git a/test/unit/tool-warning-sink.test.ts b/test/unit/tool-warning-sink.test.ts new file mode 100644 index 0000000..96ed62f --- /dev/null +++ b/test/unit/tool-warning-sink.test.ts @@ -0,0 +1,105 @@ +import { describe, expect, it } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { ipynbEditTool } from "../../src/tools/edit.js" +import { makeWarningSink } from "../../src/utils/warnings.js" +import type { ToolContext } from "../../src/tool.js" + +const makeContext = (dir: string, sink?: unknown): ToolContext => + ({ + sessionID: "test", + messageID: "test", + agent: "test", + directory: dir, + worktree: dir, + abort: new AbortController().signal, + metadata: () => {}, + ask: async () => {}, + warningSink: sink + }) as unknown as ToolContext + +const withTempDir = async (fn: (dir: string) => Promise): Promise => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "tool-sink-")) + try { + await fn(dir) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +const notebook = `{ + "cells": [ + { + "cell_type": "markdown", + "id": "a", + "metadata": {}, + "source": [ + "# A" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} +` + +describe("tool context carries the warning sink", () => { + it("edits a notebook and reports the write mode", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const sink = makeWarningSink() + const result = await ipynbEditTool.execute( + { filePath: file, cellIndex: 0, source: "# B", clearOutputs: "never" }, + makeContext(dir, sink) + ) + expect(String((result as { output: string }).output)).toContain("Edited cell [0]") + expect((result as { metadata: Record }).metadata.writeMode).toBe( + "patched" + ) + }) + }) + + it("still works when the context has no sink", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, notebook) + const result = await ipynbEditTool.execute( + { filePath: file, cellIndex: 0, source: "# C", clearOutputs: "never" }, + makeContext(dir) + ) + expect(String((result as { output: string }).output)).toContain("Edited cell [0]") + }) + }) +}) + +describe("appendWarnings surfaces collected warnings", () => { + it("renders warnings into the tool output and metadata", async () => { + const { toV2Result } = await import("../../src/plugin-v2.js") + const sink = makeWarningSink() + sink.add({ source: "lock", message: "could not canonicalize", detail: "EACCES" }) + sink.add({ source: "temp-unlink", message: "left /tmp/x.tmp" }) + const warnings = sink.drain() + expect(warnings.length).toBe(2) + + const pluginContext = { + location: { directory: "/tmp", project: { directory: "/tmp" } }, + permission: { assert: async () => {} }, + options: {} + } as never + const toolContext = { + sessionID: "s", + messageID: "m", + agent: "a", + id: "i", + signal: new AbortController().signal, + progress: async () => {} + } as never + const { toToolContext } = await import("../../src/plugin-v2.js") + const built = toToolContext(pluginContext, toolContext, undefined, makeWarningSink()) + expect(built.warningSink).toBeDefined() + expect(toV2Result({ output: "done" })).toBeDefined() + }) +}) diff --git a/test/unit/tool-wrappers.test.ts b/test/unit/tool-wrappers.test.ts index 3a0e5a0..7ff49de 100644 --- a/test/unit/tool-wrappers.test.ts +++ b/test/unit/tool-wrappers.test.ts @@ -245,6 +245,10 @@ describe("tool wrappers > happy paths", () => { describe("tool wrappers > error paths", () => { const missing = "/tmp/opencode/definitely-missing-notebook.ipynb" + const outside = + process.platform === "win32" + ? path.join(process.env.SystemRoot ?? "C:\\Windows", "ipynb-tool-wrapper-outside.ipynb") + : "/etc/ipynb-tool-wrapper-outside.ipynb" const cases: ReadonlyArray<{ name: string @@ -322,7 +326,7 @@ describe("tool wrappers > error paths", () => { run: (ctx) => execute( ipynbKernelTool, - { action: "restart", filePath: "/etc/ipynb-tool-wrapper-outside.ipynb" }, + { action: "restart", filePath: outside }, { ...ctx, pluginOptions: { diff --git a/test/unit/virtual-materialize.test.ts b/test/unit/virtual-materialize.test.ts index 70681c2..061fde5 100644 --- a/test/unit/virtual-materialize.test.ts +++ b/test/unit/virtual-materialize.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "bun:test" +import { describe, expect, it, spyOn } from "bun:test" import * as fs from "node:fs" import * as os from "node:os" import * as path from "node:path" @@ -125,6 +125,132 @@ describe("virtual notebook materialization", () => { } }) + it("does not rewrite a sidecar whose content is already current", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-materialize-")) + const file = path.join(dir, "nav.ipynb") + const document = buildNotebookVirtualDocument(notebook, { filePath: file }) + try { + const first = await materializeVirtualDocument(document, dir) + const inode = fs.statSync(first.path).ino + const original = fs.promises.rename + let renames = 0 + const spy = spyOn(fs.promises, "rename").mockImplementation((( + from: fs.PathLike, + to: fs.PathLike + ) => { + renames += 1 + return original(from, to) + }) as unknown as typeof fs.promises.rename) + try { + await materializeVirtualDocument(document, dir) + expect(renames).toBe(0) + expect(fs.statSync(first.path).ino).toBe(inode) + expect(fs.readFileSync(first.path, "utf8")).toBe(document.text) + } finally { + spy.mockRestore() + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("skips the rewrite when a refresh produces identical text", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-materialize-")) + const file = path.join(dir, "nav.ipynb") + const document = buildNotebookVirtualDocument(notebook, { filePath: file }) + try { + const first = await materializeVirtualDocument(document, dir) + const inode = fs.statSync(first.path).ino + const original = fs.promises.rename + let renames = 0 + const spy = spyOn(fs.promises, "rename").mockImplementation((( + from: fs.PathLike, + to: fs.PathLike + ) => { + renames += 1 + return original(from, to) + }) as unknown as typeof fs.promises.rename) + try { + await expect(refreshMaterializedDocument(document, dir)).resolves.toBe(true) + expect(renames).toBe(0) + expect(fs.statSync(first.path).ino).toBe(inode) + } finally { + spy.mockRestore() + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("keeps a sidecar materialized during cleanup tracked for the next sweep", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-materialize-race-")) + const fileB = path.join(dir, "b.ipynb") + const fileC = path.join(dir, "c.ipynb") + const original = fs.promises.rm + let release: () => void = () => {} + const gate = new Promise((resolve) => { + release = resolve + }) + let entered: () => void = () => {} + const rmEntered = new Promise((resolve) => { + entered = resolve + }) + const spy = spyOn(fs.promises, "rm").mockImplementation((( + target: fs.PathLike, + options?: unknown + ) => { + if (String(target).includes("opencode-ipynb-lsp-")) { + entered() + return gate.then(() => + (original as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + ) + } + return (original as unknown as (...args: unknown[]) => Promise)( + target, + options + ) + }) as unknown as typeof fs.promises.rm) + try { + const b = await materializeVirtualDocument( + buildNotebookVirtualDocument(notebook, { filePath: fileB }), + dir + ) + const cleanup = cleanupVirtualDocuments(dir) + await rmEntered + const c = await materializeVirtualDocument( + buildNotebookVirtualDocument(notebook, { filePath: fileC }), + dir + ) + release() + await cleanup + spy.mockRestore() + expect(fs.existsSync(b.path)).toBe(false) + expect(fs.existsSync(c.path)).toBe(true) + await cleanupVirtualDocuments(dir) + expect(fs.existsSync(c.path)).toBe(false) + } finally { + spy.mockRestore() + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + + it("refuses a directory at the sidecar path without creating a temp file", async () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-materialize-")) + const file = path.join(dir, "nav.ipynb") + const document = buildNotebookVirtualDocument(notebook, { filePath: file }) + fs.mkdirSync(materializedPath(file, dir)) + try { + await expect(materializeVirtualDocument(document, dir)).rejects.toThrow( + "Refusing to replace a directory" + ) + expect(fs.readdirSync(dir).filter((entry) => entry.endsWith(".tmp"))).toEqual([]) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } + }) + it("uses the real notebook identity for symlink aliases", async () => { if (process.platform === "win32") return const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-materialize-alias-")) diff --git a/test/unit/warning-reporting.test.ts b/test/unit/warning-reporting.test.ts new file mode 100644 index 0000000..7df1476 --- /dev/null +++ b/test/unit/warning-reporting.test.ts @@ -0,0 +1,341 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { makePathService } from "../../src/services/PathService.js" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { + permissionAliases, + resolveDeepReal +} from "../../src/services/PermissionService.js" +import { killWindowsTree } from "../../src/utils/windows.js" +import { makeWarningSink } from "../../src/utils/warnings.js" + +const isRoot = typeof process.getuid === "function" && process.getuid() === 0 +const canDenyByMode = process.platform !== "win32" && !isRoot + +const makeTmpDir = (prefix: string): string => + fs.mkdtempSync(path.join(os.tmpdir(), prefix)) + +const makeBlockedDir = (root: string, name: string): string => { + const blocked = path.join(root, name) + fs.mkdirSync(blocked) + fs.chmodSync(blocked, 0o000) + return blocked +} + +const unlock = (root: string): void => { + fs.chmodSync(root, 0o700) + for (const entry of fs.readdirSync(root, { withFileTypes: true })) { + if (entry.isDirectory()) unlock(path.join(root, entry.name)) + } +} + +const withCleanup = async ( + root: string, + run: () => Promise +): Promise => { + try { + await run() + } finally { + try { + unlock(root) + } catch {} + fs.rmSync(root, { recursive: true, force: true }) + } +} + +const waitForWarnings = async ( + drain: () => ReadonlyArray<{ source: string; message: string; detail?: string }> +) => { + for (let attempt = 0; attempt < 200; attempt += 1) { + const warnings = drain() + if (warnings.length > 0) return warnings + await new Promise((resolve) => setTimeout(resolve, 10)) + } + return drain() +} + +describe("PermissionService.permissionAliases > realpath failures", () => { + it("reports a realpath failure that is not a missing path", async () => { + if (!canDenyByMode) return + const root = makeTmpDir("ipynb-warn-alias-") + const blocked = makeBlockedDir(root, "blocked") + const sink = makeWarningSink() + try { + const aliases = await permissionAliases( + path.join(blocked, "new.ipynb"), + [root], + { warningSink: sink } + ) + expect(aliases).toContain(path.join(blocked, "new.ipynb")) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("permission-alias") + expect(warnings[0]?.detail).toContain("EACCES") + } finally { + await withCleanup(root, async () => {}) + } + }) + + it("stays quiet for a path that does not exist yet", async () => { + if (process.platform === "win32") return + const root = makeTmpDir("ipynb-warn-alias-quiet-") + const sink = makeWarningSink() + try { + const aliases = await permissionAliases( + path.join(root, "missing", "new.ipynb"), + [root], + { warningSink: sink } + ) + expect(aliases.length).toBeGreaterThan(0) + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) +}) + +describe("NotebookFileService.withFileLock > canonicalization failures", () => { + it("reports a lock key it could not canonicalize", async () => { + if (!canDenyByMode) return + const root = makeTmpDir("ipynb-warn-lock-") + const blocked = makeBlockedDir(root, "blocked") + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + try { + const value = await Effect.runPromise( + svc.withFileLock(path.join(blocked, "x.ipynb"), Effect.succeed(7)) + ) + expect(value).toBe(7) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("lock") + expect(warnings[0]?.detail).toContain("EACCES") + } finally { + await withCleanup(root, async () => {}) + } + }) + + it("stays quiet for a notebook that does not exist yet", async () => { + if (process.platform === "win32") return + const root = makeTmpDir("ipynb-warn-lock-quiet-") + const sink = makeWarningSink() + const svc = makeNotebookFileService({ warningSink: sink }) + try { + await Effect.runPromise( + svc.withFileLock(path.join(root, "missing.ipynb"), Effect.succeed(1)) + ) + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) +}) + +describe("PermissionService.resolveDeepReal", () => { + it("reports the first unreadable ancestor once and still returns a path", async () => { + if (!canDenyByMode) return + const root = makeTmpDir("ipynb-warn-deep-") + const blocked = makeBlockedDir(root, "blocked") + const sink = makeWarningSink() + try { + const resolved = await resolveDeepReal( + path.join(blocked, "nested", "new.ipynb"), + { warningSink: sink } + ) + expect(resolved.endsWith(path.join("nested", "new.ipynb"))).toBe(true) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("permission-alias") + } finally { + await withCleanup(root, async () => {}) + } + }) + + it("stays quiet for a not-yet-existing path", async () => { + if (process.platform === "win32") return + const root = makeTmpDir("ipynb-warn-deep-quiet-") + const sink = makeWarningSink() + try { + await resolveDeepReal(path.join(root, "missing", "new.ipynb"), { + warningSink: sink + }) + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) +}) + +describe("PathService.ensureInsideWorktree > unreadable components", () => { + it("reports an unreadable component it had to skip", async () => { + if (!canDenyByMode) return + const root = makeTmpDir("ipynb-warn-confinement-") + const blocked = makeBlockedDir(root, "blocked") + const sink = makeWarningSink() + const pathSvc = makePathService({ + directory: root, + worktree: root, + platform: process.platform, + warningSink: sink + }) + try { + await Effect.runPromise( + pathSvc.ensureInsideWorktree(path.join(blocked, "n.ipynb")) + ) + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("path-resolution") + expect(warnings[0]?.detail).toContain("EACCES") + } finally { + await withCleanup(root, async () => {}) + } + }) + + it("reports a worktree root it could not resolve", async () => { + if (!canDenyByMode) return + const root = makeTmpDir("ipynb-warn-root-") + const blocked = makeBlockedDir(root, "blocked") + const worktree = path.join(blocked, "work") + const sink = makeWarningSink() + const pathSvc = makePathService({ + directory: worktree, + worktree, + platform: process.platform, + warningSink: sink + }) + try { + const exit = await Effect.runPromiseExit( + pathSvc.ensureInsideWorktree(path.join(worktree, "n.ipynb")) + ) + expect(exit._tag).toBe("Failure") + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("path-resolution") + expect(warnings[0]?.detail).toContain("EACCES") + } finally { + await withCleanup(root, async () => {}) + } + }) + + it("stays quiet while walking ancestors that do not exist yet", async () => { + if (process.platform === "win32") return + const root = makeTmpDir("ipynb-warn-confinement-quiet-") + const sink = makeWarningSink() + const pathSvc = makePathService({ + directory: root, + worktree: root, + platform: process.platform, + warningSink: sink + }) + try { + await Effect.runPromise( + pathSvc.ensureInsideWorktree(path.join(root, "missing", "deep", "n.ipynb")) + ) + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) +}) + +describe("PathService.ensureExists > unreadable paths", () => { + it("reports an unreadable path that looks missing", async () => { + if (!canDenyByMode) return + const root = makeTmpDir("ipynb-warn-exists-") + const blocked = makeBlockedDir(root, "blocked") + const sink = makeWarningSink() + const pathSvc = makePathService({ + directory: root, + worktree: root, + platform: process.platform, + warningSink: sink + }) + try { + const error = await Effect.runPromise( + pathSvc.ensureExists(path.join(blocked, "n.ipynb")).pipe(Effect.flip) + ) + expect(error._tag).toBe("NotebookNotFound") + expect(error.message).toBe("file does not exist") + const warnings = sink.drain() + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("path-resolution") + expect(warnings[0]?.detail).toContain("EACCES") + } finally { + await withCleanup(root, async () => {}) + } + }) + + it("stays quiet for a path that is genuinely absent", async () => { + if (process.platform === "win32") return + const root = makeTmpDir("ipynb-warn-exists-quiet-") + const sink = makeWarningSink() + const pathSvc = makePathService({ + directory: root, + worktree: root, + platform: process.platform, + warningSink: sink + }) + try { + const error = await Effect.runPromise( + pathSvc.ensureExists(path.join(root, "absent.ipynb")).pipe(Effect.flip) + ) + expect(error._tag).toBe("NotebookNotFound") + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) +}) + +describe("PathService.writeFileSafe > mode probing", () => { + it("keeps the resolved env free of the sink", () => { + const sink = makeWarningSink() + const pathSvc = makePathService({ + directory: "/foo", + worktree: "/foo", + platform: process.platform, + warningSink: sink + }) + expect(pathSvc.env).toEqual({ + directory: "/foo", + worktree: "/foo", + platform: process.platform + }) + }) + + it("stays quiet when the target does not exist and when it is a regular file", async () => { + if (process.platform === "win32") return + const root = makeTmpDir("ipynb-warn-write-quiet-") + const sink = makeWarningSink() + const pathSvc = makePathService({ + directory: root, + worktree: root, + platform: process.platform, + warningSink: sink + }) + try { + const file = path.join(root, "out.txt") + await Effect.runPromise(pathSvc.writeFileSafe(file, "one")) + await Effect.runPromise(pathSvc.writeFileSafe(file, "two")) + expect(fs.readFileSync(file, "utf8")).toBe("two") + expect(sink.drain()).toEqual([]) + } finally { + fs.rmSync(root, { recursive: true, force: true }) + } + }) +}) + +describe("windows.killWindowsTree > spawn failures", () => { + it("reports a taskkill process that could not be started", async () => { + if (process.platform === "win32") return + const sink = makeWarningSink() + killWindowsTree(4242, sink) + const warnings = await waitForWarnings(sink.drain) + expect(warnings).toHaveLength(1) + expect(warnings[0]?.source).toBe("cleanup") + expect(warnings[0]?.message).toContain("taskkill") + }) +}) diff --git a/test/unit/warnings.test.ts b/test/unit/warnings.test.ts new file mode 100644 index 0000000..b19b837 --- /dev/null +++ b/test/unit/warnings.test.ts @@ -0,0 +1,103 @@ +import { describe, expect, it } from "bun:test" +import { Effect } from "effect" +import { + bestEffort, + ignoreExpectedFailure, + makeWarningSink, + warningFrom +} from "../../src/utils/warnings.js" + +describe("warning sink", () => { + it("collects warnings until drained", () => { + const sink = makeWarningSink() + sink.add({ source: "lock", message: "boom" }) + expect(sink.drain()).toEqual([{ source: "lock", message: "boom" }]) + expect(sink.drain()).toEqual([]) + }) + + it("drain returns a copy, not the live buffer", () => { + const sink = makeWarningSink() + sink.add({ source: "lock", message: "a" }) + const first = sink.drain() + sink.add({ source: "lock", message: "b" }) + expect(first.length).toBe(1) + }) +}) + +describe("warningFrom", () => { + it("uses the Error message", () => { + expect(warningFrom("lock", new Error("nope"))).toEqual({ + source: "lock", + message: "nope" + }) + }) + + it("stringifies non-Errors", () => { + expect(warningFrom("lock", 42)).toEqual({ source: "lock", message: "42" }) + }) + + it("keeps the errno code and the context", () => { + const error = new Error("gone") as NodeJS.ErrnoException + error.code = "ENOENT" + expect(warningFrom("temp-unlink", error, "removing tmp")).toEqual({ + source: "temp-unlink", + message: "gone", + detail: "removing tmp: ENOENT" + }) + }) +}) + +describe("ignoreExpectedFailure", () => { + it("passes the value through on success", async () => { + const sink = makeWarningSink() + const value = await Effect.runPromise( + ignoreExpectedFailure(sink, "path-resolution", "probe", Effect.succeed(7)) + ) + expect(value).toBe(7) + expect(sink.drain()).toEqual([]) + }) + + it("records the failure and returns undefined", async () => { + const sink = makeWarningSink() + const value = await Effect.runPromise( + ignoreExpectedFailure( + sink, + "path-resolution", + "probe", + Effect.fail(new Error("denied")) + ) + ) + expect(value).toBeUndefined() + expect(sink.drain()).toEqual([ + { source: "path-resolution", message: "denied", detail: "probe: denied" } + ]) + }) + + it("works without a sink", async () => { + const value = await Effect.runPromise( + ignoreExpectedFailure( + undefined, + "path-resolution", + "probe", + Effect.fail(new Error("denied")) + ) + ) + expect(value).toBeUndefined() + }) +}) + +describe("bestEffort", () => { + it("records a rejected promise instead of swallowing it", async () => { + const sink = makeWarningSink() + await bestEffort(sink, "cleanup", "dispose", () => Promise.reject(new Error("late"))) + expect(sink.drain()).toEqual([ + { source: "cleanup", message: "late", detail: "dispose: late" } + ]) + }) + + it("stays quiet on success", async () => { + const sink = makeWarningSink() + await bestEffort(sink, "cleanup", "dispose", () => Promise.resolve()) + expect(sink.drain()).toEqual([]) + }) +}) diff --git a/test/unit/write-idempotency.test.ts b/test/unit/write-idempotency.test.ts new file mode 100644 index 0000000..f282f90 --- /dev/null +++ b/test/unit/write-idempotency.test.ts @@ -0,0 +1,119 @@ +import { afterEach, describe, expect, it, spyOn } from "bun:test" +import * as fs from "node:fs" +import * as os from "node:os" +import * as path from "node:path" +import { Effect } from "effect" +import { makeNotebookFileService } from "../../src/services/NotebookFileService.js" +import { detectNotebookFormat } from "../../src/utils/json.js" + +const run = async (effect: Effect.Effect) => + Effect.runPromise(effect as Effect.Effect) + +const withTempDir = async (fn: (dir: string) => Promise): Promise => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "ipynb-idem-")) + try { + await fn(dir) + } finally { + fs.rmSync(dir, { recursive: true, force: true }) + } +} + +const notebook = (source: string): Record => ({ + cells: [{ cell_type: "markdown", metadata: {}, source: [source] }], + metadata: {}, + nbformat: 4, + nbformat_minor: 5 +}) + +const serialized = (source: string): string => + `${JSON.stringify(notebook(source), null, 1)}\n` + +describe("writeAtomic idempotency", () => { + const restore: Array<() => void> = [] + + afterEach(() => { + while (restore.length > 0) restore.pop()?.() + }) + + it("does not touch the filesystem when the stored rewrite is byte-identical", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, serialized("# A")) + const svc = makeNotebookFileService() + const spy = spyOn(fs.promises, "rename") + restore.push(() => spy.mockRestore()) + const outcome = await run(svc.writeAtomic(file, notebook("# A") as never)) + expect(spy).not.toHaveBeenCalled() + expect(fs.readFileSync(file, "utf8")).toBe(serialized("# A")) + expect(outcome.mode).toBe("patched") + }) + }) + + it("verifies the revision, then skips an identical rewrite", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, serialized("# A")) + const text = fs.readFileSync(file, "utf8") + const svc = makeNotebookFileService() + const spy = spyOn(fs.promises, "rename") + restore.push(() => spy.mockRestore()) + const outcome = await run( + svc.writeAtomic(file, notebook("# A") as never, { + format: detectNotebookFormat(text), + previousText: text + }) + ) + expect(spy).not.toHaveBeenCalled() + expect(fs.readFileSync(file, "utf8")).toBe(text) + expect(outcome.mode).toBe("patched") + }) + }) + + it("still rejects an identical rewrite when the notebook changed meanwhile", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, serialized("# A")) + const stale = fs.readFileSync(file, "utf8") + fs.writeFileSync(file, serialized("# B")) + const svc = makeNotebookFileService() + const exit = await Effect.runPromiseExit( + svc.writeAtomic(file, notebook("# A") as never, { + format: detectNotebookFormat(stale), + previousText: stale + }) + ) + expect(exit._tag).toBe("Failure") + expect(fs.readFileSync(file, "utf8")).toBe(serialized("# B")) + }) + }) + + it("still writes when the notebook content differs", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, serialized("# A")) + const svc = makeNotebookFileService() + const spy = spyOn(fs.promises, "rename") + restore.push(() => spy.mockRestore()) + await run(svc.writeAtomic(file, notebook("# B") as never)) + expect(spy).toHaveBeenCalled() + expect(fs.readFileSync(file, "utf8")).toContain("# B") + }) + }) + + it("recreates a deleted notebook even when the rewrite is identical", async () => { + await withTempDir(async (dir) => { + const file = path.join(dir, "n.ipynb") + fs.writeFileSync(file, serialized("# A")) + const stale = fs.readFileSync(file, "utf8") + fs.rmSync(file) + const svc = makeNotebookFileService() + await run( + svc.writeAtomic(file, notebook("# A") as never, { + format: detectNotebookFormat(stale), + previousText: stale + }) + ) + expect(fs.readFileSync(file, "utf8")).toBe(serialized("# A")) + }) + }) +})