diff --git a/README.md b/README.md index 196748a..c928605 100644 --- a/README.md +++ b/README.md @@ -27,6 +27,18 @@ through `open()` on arbitrary host paths. - **`match` statements** — pattern matching is not implemented. - **class inheritance and metaclasses** — a plain `class` with methods and `__init__` works, but `class B(A)` raises `NotImplementedError`. +- **`del`** — the `del` statement is not implemented. + +A refusal is all-or-nothing: the parser and the type checker both run before the first statement, +so a rejected construct discards the whole snippet — nothing in it runs and no side effect happens. + +**Type checker.** A static type check runs before execution and fails as `[error: typing]`. Missing +names are typing errors, not catchable `NameError`s (`ImportError` and `ModuleNotFoundError` are +themselves rejected by the checker, and a refused import never runs). `map`, `filter`, `getattr`, +`hasattr` and `setattr` exist at runtime but the checker rejects them; a longer list of names is +absent from both — `skills/repl-simple/SKILL.md` carries the measured lists. I/O is `print()`-only +(`sys.stdout.write`/`sys.stderr.write` and `os.environ`/`os.getenv` raise at runtime), and only +class objects carry `__name__` — functions, builtins and instances expose no dunder methods. **Returned values.** The value a snippet ends on crosses to the host as data, with two limits on Monty 0.0.23. Nesting is capped: a list 48 levels deep and a class instance 24 deep are fine, and @@ -52,7 +64,8 @@ Sessions are pooled per project directory, with a **cap of 32 live sessions** an when a new one would exceed it: the session used least recently is dropped first. The knobs, in precedence order: `ReplRunnerOptions.maxSessions` (embedders) > `REPL_MAX_SESSIONS` env (positive integer) > 32. A dropped session is gone — its variables, imports and cache are released, and the -next `repl` call on that id starts fresh. +next `repl` call on that id starts fresh. That first call carries a one-shot `[evicted]` notice +naming the cap, so the model is not left guessing why its variables vanished. **A session with a pending approval is never evicted, and neither is one whose call is still running.** Evicting either would discard a call the user was asked to approve — or may be about to diff --git a/docs/path-jail.md b/docs/path-jail.md index 2c73145..49fa51f 100644 --- a/docs/path-jail.md +++ b/docs/path-jail.md @@ -81,7 +81,10 @@ Two tools deliberately have none: exactly the path it is given, which the argument jail has already canonicalised. - **`find`** only consults its operations when they supply `glob`, which replaces the `fd` subprocess entirely — losing .gitignore handling and the result caps with it. `fd`, like `rg`, - does not follow symlinks out of the tree it is pointed at. + does not follow symlinks out of the tree it is pointed at. The bridge refuses an absolute + `pattern` (or one containing a `..` segment) before `fd` runs, so the model gets a refusal it + can act on instead of fd's "no files found": the pattern is not a `path` and never reaches the + jail described above. A caller's own `operations` still compose: the jail wraps them, and they see canonical, in-root paths or nothing at all. diff --git a/docs/review-59.md b/docs/review-59.md index a89e47e..cdefb95 100644 --- a/docs/review-59.md +++ b/docs/review-59.md @@ -51,7 +51,8 @@ All four review findings were fixed in `59.5` and `59.6` (tests added first, RED - **Verified** `src/repl.ts:269-284`: the `for (;;)` loop's `existing !== undefined` correctly distinguishes trust-discard rebuilds (notice) from eviction-recreation (no notice); the revalidation `continue` cannot busy-spin (every iteration awaits a trust check, and each - `continue` requires another caller to have changed the map). + `continue` requires another caller to have changed the map). (Superseded in part: + eviction-recreation now carries a one-shot `[evicted]` notice.) - **Verified** `src/repl.ts:296-311`: `inflight.delete` and `insert` run in the same synchronous `.then`, so no caller can miss both maps; concurrent joiners of a failing creation all reject together, which is correct (the creation genuinely failed; only *later* callers retry). diff --git a/docs/ship-59.md b/docs/ship-59.md index 299ea17..5ccf758 100644 --- a/docs/ship-59.md +++ b/docs/ship-59.md @@ -52,7 +52,10 @@ mutant changes no observable behavior (every access re-checks trust). None in the single-flight, LRU, or eviction-skip logic. 3. **Silent eviction for idle sessions** (no model-facing notice when an evicted id comes back - fresh) — not requested by #59; observe in practice before adding a tombstone. + fresh) — not requested by #59; observe in practice before adding a tombstone. **Observed and + resolved**: the live e2e run showed sessions vanishing with no explanation, and the pool now + keeps a bounded tombstone that delivers a one-shot `[evicted]` notice on the next + `repl`/`repl_resume` call for a dropped id. 4. **Concurrent same-id runs through the direct API** replay from the same starting snapshot — unreachable via the shipped extension (`executionMode: "sequential"`); inherent to replay-based sessions, belongs to #61 if it ever matters. diff --git a/extensions/repl-extension.ts b/extensions/repl-extension.ts index 3e5bb6d..d041b4d 100644 --- a/extensions/repl-extension.ts +++ b/extensions/repl-extension.ts @@ -1536,6 +1536,9 @@ export default function (pi: ReplExtensionApi) { "with no pause points runs until the duration limit (maxDurationSecs). " + `One repl or repl_resume call opens at most ${MAX_DIALOGS_PER_CALL} approval ` + "dialogs; gated calls past that are denied and the result says why. " + + "At most 32 live sessions are pooled per project by default (REPL_MAX_SESSIONS); " + + "past that cap the oldest session that is not awaiting approval is dropped, and the " + + "next call on that id starts fresh with an [evicted] notice. " + "The sessionId is scoped to this Pi session: when the conversation ends " + "(/new, /resume, /fork, quit) every REPL session is disposed, a pending approval " + "is dropped, and the same sessionId in the next conversation is a new, empty REPL.", @@ -1552,7 +1555,8 @@ export default function (pi: ReplExtensionApi) { description: "Maximum interpreter compute time in seconds, capped at 300, or lower if the " + "operator sets REPL_MAX_DURATION_SECS (default 30). " + - "Omitted uses the sandbox default (30).", + "Omitted uses the sandbox default (30); 0, a negative or a non-finite value " + + "is treated as omitted.", }), ), maxMemory: Type.Optional( @@ -1560,7 +1564,8 @@ export default function (pi: ReplExtensionApi) { description: "Maximum sandbox heap in MiB, capped at 1024, or lower if the operator sets " + "REPL_MAX_MEMORY_MB (default 512 MiB). " + - "Omitted uses the sandbox default (512 MiB).", + "Omitted uses the sandbox default (512 MiB); 0, a negative or a non-finite " + + "value is treated as omitted.", }), ), }), diff --git a/skills/repl-simple/SKILL.md b/skills/repl-simple/SKILL.md index 98ff2e5..c74c864 100644 --- a/skills/repl-simple/SKILL.md +++ b/skills/repl-simple/SKILL.md @@ -18,6 +18,8 @@ Sandboxed Python execution in pi via [Monty](https://github.com/pydantic/monty) - `maxDurationSecs`: interpreter compute seconds, default 30, cap 300. - `maxMemory`: sandbox heap MiB, default 512, cap 1024. +- A non-positive or non-finite limit is treated as omitted (the fail-safe default applies) — `maxDurationSecs=0` is not a limit of zero. +- Sessions are pooled per project: at most 32 live (`REPL_MAX_SESSIONS`); the least-recently-used is evicted — never one with a pending approval — and the next call on that id starts fresh with a one-shot `[evicted]` notice. - A `repl` or `repl_resume` call opens at most **8 approval dialogs**; gated calls past that are denied and the result says so. - Running new `repl` code while a call is suspended discards that call — `repl_resume` first if you still want it. - Sessions are scoped to one pi conversation: `/new`, `/resume`, `/fork`, or quit disposes every session and drops pending approvals. The same `sessionId` next conversation is a fresh, empty REPL. @@ -55,10 +57,16 @@ The sandbox has no filesystem of its own: `open()`, `os.listdir()`, and `pathlib - `match` statements (no pattern matching) - class inheritance / metaclasses (`class B(A)` fails; a plain `class` with methods works) +A construct the parser or checker refuses discards the whole snippet — no statement in it runs, and no side effect happens. + **Type-checker limits** (a static type check runs before execution and fails as `[error: typing]`, distinct from `[error: syntax]`/`[error: runtime]`): -- Some builtins are blocked by the checker: `dir`, `callable`, `eval`, `exec`, `vars`, `globals`, `locals`, `bytearray` do not exist at runtime, while `getattr`, `hasattr`, `setattr`, `map`, `filter` exist at runtime but the checker rejects them — either way a missing name is a typing error, **not** a catchable `NameError`, so `try/except NameError` will not save you. -- Stdlib stubs are partial: `sys.maxsize`, `asyncio.sleep`, and `pathlib.PurePath` are missing, and modules have no `__dict__`. -- Lambda parameters infer as `object`: `lambda a, b: a + b` is rejected (unsupported `+`) — use a `def` with annotated parameters instead. +- Rejected by the checker **and** absent at runtime — a missing name is a typing error, **not** a catchable `NameError`, so `try/except NameError` will not save you: `dir`, `vars`, `callable`, `format`, `issubclass`, `super`, `classmethod`, `staticmethod`, `memoryview`, `complex`, `compile`, `eval`, `exec`, `globals`, `locals`, `input`, `breakpoint`, `__import__`, `bytearray`. +- Rejected by the checker but **present** at runtime (measured with the checker off), so a normal type-checked run still cannot use them: `map`, `filter`, `getattr`, `hasattr`, `setattr`. +- `ImportError` and `ModuleNotFoundError` exist at runtime but are rejected by the checker — and a refused import never runs, so there is nothing to catch. +- Stdlib stubs are partial: `os.getcwd`, `os.path`, `sys.argv`, `sys.exit`, `sys.path`, `sys.maxsize`, `collections.OrderedDict`, `asyncio.sleep`, `itertools.product`/`permutations`/`combinations`, `functools.wraps`/`lru_cache` and `pathlib.PurePath` are missing, and modules have no `__dict__`. +- Lambda parameters passed as callbacks infer as `object`: a body that uses them (`a + b`, `p[0]`, `len(w)`) is rejected in some positions — `functools.reduce(lambda …)` passes as a bare expression and fails inside `print(...)`, and `max`/`min(..., key=lambda …)` behave the same way. `sorted(..., key=…)` and `list.sort(key=…)` are accepted, and a lambda called directly is always fine. Use a `def` with annotated parameters when the callback uses its arguments. +- I/O is `print()`-only: `sys.stdout.write`/`sys.stderr.write` and `os.environ`/`os.getenv` pass the checker but raise at runtime. +- Only class objects carry `__name__` (and `type(x).__name__`); functions, builtins and instances expose no dunder methods. **Return values** cross to the host as data, with nesting caps: a list ~48 levels deep or a class instance ~24 deep is fine, one more fails the whole run with `RuntimeError: Max output depth exceeded` (after side effects). Instances cross **without their methods** — `__repr__` is not called, so end a snippet on `repr(obj)` to see a useful value. diff --git a/src/bridge.ts b/src/bridge.ts index b854276..4b5dab9 100644 --- a/src/bridge.ts +++ b/src/bridge.ts @@ -363,6 +363,23 @@ async function jailPathArg( return { ...args, path: await jail.resolve(raw) }; } +/** + * Whether a glob is absolute or climbs out of the project root. + * + * An honesty guard, not an escape guard: both `fd` and `rg` walk only the + * jailed search path, so a pattern like `/etc/*` comes back as "no files + * found" / "no matches found" — an empty result the model reads as fact. + * Absolute patterns are refused even when they happen to name an in-root + * path, because accepting some would mean resolving them against the jail + * first; the rule is simply "project-relative globs". Both separators are + * checked so the guard does not stop at the platform boundary. + */ +function notProjectRelative(pattern: string): boolean { + if (pattern.startsWith("/") || pattern.startsWith("\\")) return true; + if (/^[A-Za-z]:[\\/]/.test(pattern)) return true; + return pattern.split(/[\\/]/).includes(".."); +} + interface ToolSpec { name: string; /** @@ -472,6 +489,19 @@ const TOOL_SPECS: ToolSpec[] = [ }, ], mutating: false, + // The same honesty guard as `find`: a `glob` is not a `path`, so an + // absolute one never reaches the jail and rg answers "No matches found" + // — an empty result the model reads as fact. + prepareArgs: (args) => { + const glob = args.glob; + if (typeof glob === "string" && notProjectRelative(glob)) { + throw new HostToolError( + "PermissionError", + `the grep glob '${glob}' is not project-relative; use a glob inside the project root`, + ); + } + return args; + }, }, { name: "find", @@ -487,6 +517,21 @@ const TOOL_SPECS: ToolSpec[] = [ { name: "limit", type: "int", description: "Maximum number of results.", optional: true }, ], mutating: false, + // `path` is jailed above; `pattern` is not a path and never reaches the + // jail, so a glob pointing outside the root would be answered with "No + // files found matching pattern" — a refusal-shaped fact the model would + // act on. Refuse it by name instead. + prepareArgs: (args) => { + const pattern = args.pattern; + if (typeof pattern === "string" && notProjectRelative(pattern)) { + throw new HostToolError( + "PermissionError", + `the find pattern '${pattern}' is not project-relative; use a glob inside the ` + + "project root (e.g. '*.ts' with an optional jailed 'path')", + ); + } + return args; + }, }, { name: "ls", diff --git a/src/registry.ts b/src/registry.ts index d66710a..1bd2e11 100644 --- a/src/registry.ts +++ b/src/registry.ts @@ -498,7 +498,8 @@ export const TY_GAP_REASONS: Readonly> = { * rejects as unresolved. These need `name: Any = None` declarations * in the type-check stubs. * - * The gaps did **not** close on 0.0.21 — measured, all six still report + * The gaps did **not** close on 0.0.21 — measured, all six names in the list + * then (five today; see `TY_GAP_REASONS` for why `bytearray` left) reported * `unresolved-reference`. What changed is where the declaration goes: into * out-of-band `typeCheckStubs` rather than a prefix prepended to the user's * source, so it no longer shifts the line numbers in reported diagnostics @@ -555,8 +556,11 @@ export function renderPythonToolRules(importableModules: string[]): string { - The value of the last top-level expression is returned as the result (expressions inside if/try blocks are not). - Imports: these modules are available: ${importableModules.join(", ")}. Anything else - (e.g. ${blocked.join(", ")}) is refused before your code runs (a type-check error, - error[unresolved-import]) — you cannot except it; delete the import and retry. + (e.g. ${blocked.join(", ")}) is refused before your code runs — a typing error named + \`unresolved-import\`, never a catchable ImportError — and there are no third-party + packages. Delete the import and retry. +- I/O is print()-only: sys.stdout.write, sys.stderr.write, os.environ and os.getenv + raise at runtime even though the checker accepts them. - To read, list, or search PROJECT files, use the tools (read, grep, find, ls, read_file, list_files) — never open(), os.listdir(), or pathlib. By default the sandbox has no filesystem (open()/os.listdir()/pathlib raise PermissionError) @@ -568,6 +572,12 @@ export function renderPythonToolRules(importableModules: string[]): string { denied in the RLM loop) — do not call them. - Class inheritance, metaclasses, match statements, and yield/generators are not supported (NotImplementedError); a plain class with __init__ and methods works. + A construct the parser or checker refuses discards the whole snippet — nothing in it runs. +- Lambda callbacks get object parameters: when the body uses them (a + b, p[0], len(w)), + pass an annotated def — reduce/max/min reject such callbacks in some positions, while + sorted(..., key=lambda ...) and list.sort(key=...) are accepted. +- Only class objects carry \`__name__\` (and \`type(x).__name__\`); functions, builtins and + instances expose no dunder methods. - Tool failures raise normal Python exceptions you can catch (e.g. ValueError, FileNotFoundError, OSError).`; } diff --git a/src/repl.ts b/src/repl.ts index ea1037c..d349d94 100644 --- a/src/repl.ts +++ b/src/repl.ts @@ -407,6 +407,17 @@ interface LiveSession { */ const DEFAULT_MAX_SESSIONS = 32; +/** + * How many evicted ids the pool remembers so the next `run`/`resume` on one + * can say why it is fresh. + * + * The pool itself is capped, so a long conversation evicts steadily; an + * unbounded tombstone map would trade one unbounded map for another. Past + * this bound the ordinary `no-session` sentence answers — what the model got + * before the notice existed — rather than pretending nothing was dropped. + */ +const EVICTION_TOMBSTONES = 64; + /** Positive integer or fallback — the same rule `src/pool.ts` applies. */ function envInt(name: string, fallback: number): number { const raw = process.env[name]; @@ -447,6 +458,14 @@ export class ReplRunner { private cwd: string; private isProjectTrusted: () => boolean; private maxSessions: number; + /** + * Ids the cap dropped, newest last, bounded to `EVICTION_TOMBSTONES`. + * + * `reset` and a trust-change rebuild delete their entry directly rather + * than through `insert`, so only a cap eviction leaves a tombstone — which + * is exactly the case the model cannot otherwise explain. + */ + private readonly evicted = new Set(); /** This project's accepted-set manifest (#198). Never touched while the project is untrusted. */ private manifest: PreambleManifestStore; /** `onPreambleStoreInsideProject` with this runner's two paths bound; a no-op when unset. */ @@ -586,12 +605,20 @@ export class ReplRunner { signal?: AbortSignal, limits?: RunLimits | "unbounded", ): Promise { - const noSession = (): RunTrace => ({ - text: `No session '${sessionId}' exists. Run some code first.`, - sessionId, - status: "no-session", - calls: [], - }); + const noSession = (): RunTrace => { + // An id the cap dropped gets the eviction answer: "no session" is true + // but useless when the pool is the reason. One-shot, like the run-path + // notice — consumed here so a later `run` does not repeat it. + const evicted = this.evicted.delete(sessionId); + return { + text: evicted + ? evictedMessage(sessionId, this.maxSessions, "resume") + : `No session '${sessionId}' exists. Run some code first.`, + sessionId, + status: "no-session", + calls: [], + }; + }; const live = this.sessions.get(sessionId); if (!live) return noSession(); this.touch(sessionId, live); @@ -849,6 +876,7 @@ export class ReplRunner { this.attachTrustChangeNotice(sessionId, existing); trustChanged = false; } + this.attachEvictionNotice(sessionId, existing); return existing; } // trustChangeDiscards deleted the entry. The replacement must say so @@ -881,6 +909,21 @@ export class ReplRunner { live.notice = live.notice === undefined ? message : `${message}\n\n${live.notice}`; } + /** + * Deliver the one-shot `[evicted]` notice when an id the cap dropped comes + * back. + * + * Eviction is silent by design — the pool must not exceed its cap — which + * left the model holding an id and believing its variables were there. The + * tombstone is what turns that next call into an explanation, and it is + * consumed here, once, like every other notice. + */ + private attachEvictionNotice(sessionId: string, live: LiveSession): void { + if (!this.evicted.delete(sessionId)) return; + const message = evictedMessage(sessionId, this.maxSessions, "run"); + live.notice = live.notice === undefined ? message : `${message}\n\n${live.notice}`; + } + /** * Join the in-flight creation for `sessionId`, or start one. */ @@ -939,10 +982,28 @@ export class ReplRunner { if (entry.session.isSuspended()) continue; if (entry.busy > 0) continue; this.sessions.delete(key); + this.rememberEviction(key); if (this.sessions.size <= this.maxSessions) return; } } + /** + * Remember that the cap — not a reset — dropped `sessionId`. + * + * Insertion-ordered and bounded: re-evicting an id moves it to the newest + * position, and the oldest tombstone is forgotten once the bound is + * reached, so the memory cost stays a constant. + */ + private rememberEviction(sessionId: string): void { + this.evicted.delete(sessionId); + this.evicted.add(sessionId); + while (this.evicted.size > EVICTION_TOMBSTONES) { + const oldest = this.evicted.values().next().value; + if (oldest === undefined) break; + this.evicted.delete(oldest); + } + } + /** * Bring a live session into line with the trust decision in force now. * @@ -1429,6 +1490,25 @@ function trustChangedMessage(sessionId: string, lostSuspension: boolean): string ); } +/** + * Why a session id is fresh after the pool dropped it. + * + * `purpose` keeps the resume sentence honest: a resume has nothing to + * continue, while a run starts over. + */ +function evictedMessage(sessionId: string, maxSessions: number, purpose: "run" | "resume"): string { + // "the oldest session the pool could drop", not "the least recently used": + // `insert` skips suspended and busy entries, so a more recent session can + // outlive a less recent one — the statement must stay true in that state. + const head = + `[evicted] Session '${sessionId}' was the oldest session the pool could drop, so it was ` + + `dropped to stay within the ${maxSessions}-session cap.`; + return purpose === "resume" + ? `${head} There is nothing to resume — run code with repl to start a fresh session.` + : `${head} It starts fresh: variables, imports and cached tool calls are gone. ` + + `Raise REPL_MAX_SESSIONS (or ReplRunnerOptions.maxSessions) to keep more sessions.`; +} + /** Prepend a session's one-shot notice to a result, and consume it. */ function withNotice(live: LiveSession, body: string): string { const notice = live.notice; diff --git a/test/bridge.test.ts b/test/bridge.test.ts index fc95a3c..d6630a1 100644 --- a/test/bridge.test.ts +++ b/test/bridge.test.ts @@ -453,6 +453,16 @@ describe("createPiBridgeTools — the cwd jail", () => { ["grep", { pattern: SECRET, path: "escape-dir" }], ["ls", { path: "escape-dir" }], ["find", { pattern: "secret.txt", path: "escape-dir" }], + // The pattern is a glob, not a `path`, so the jail never sees these: + // they are refused by name rather than silently matching nothing and + // reading as "this directory has no files". + ["find", { pattern: "/etc/*" }], + ["find", { pattern: "../*.md" }], + ["find", { pattern: "..\\..\\secret" }], + ["find", { pattern: "C:\\etc\\*" }], + // Same class one tool over: an absolute `glob` filters rg's walk to + // nothing and the model reads "No matches found" as fact. + ["grep", { pattern: "hi", glob: "/etc/*" }], ["read_file", { path: "escape-link" }], ["list_files", { path: "escape-dir" }], ]; @@ -471,6 +481,33 @@ describe("createPiBridgeTools — the cwd jail", () => { } }); + it("refuses a non-relative glob by name, but keeps '..' inside a name", async () => { + // The guard exists so the model gets a refusal instead of "no files + // found" — and it must not swallow legitimate names: a file called + // 'a..b.txt' is not a traversal, and neither is a directory called 'a..b'. + writeFileSync(join(tmpDir, "a..b.txt"), "dots\n"); + mkdirSync(join(tmpDir, "a..b"), { recursive: true }); + writeFileSync(join(tmpDir, "a..b", "inner.md"), "inner\n"); + const tools = createPiBridgeTools(tmpDir); + const find = findTool(tools, "find"); + + assert.match(await find.execute({ pattern: "a..b.txt" }), /a\.\.b\.txt/); + assert.match(await find.execute({ pattern: "a..b/*.md" }), /inner\.md/); + + await assert.rejects( + async () => find.execute({ pattern: "/etc/*" }), + (err: unknown) => { + assert.ok(err instanceof HostToolError, `got ${err}`); + assert.equal((err as HostToolError).pythonType, "PermissionError"); + // The wording is the model's only actionable part, so it is pinned — + // and it must not claim an in-root absolute pattern was outside. + assert.match(String((err as Error).message), /not project-relative/); + assert.doesNotMatch(String((err as Error).message), /outside the search root/); + return true; + }, + ); + }); + it("is one implementation, shared by both readers", async () => { // Asserted by construction rather than by behaviour: two jails that agree // today are two jails that can disagree tomorrow, and the one nobody diff --git a/test/extension.test.ts b/test/extension.test.ts index 587ae9f..5c5373d 100644 --- a/test/extension.test.ts +++ b/test/extension.test.ts @@ -785,6 +785,24 @@ describe("repl extension — parameter schemas", () => { repl.parameters.properties.maxMemory?.description ?? "", /capped at 1024, or lower/, ); + // A model that asks for 0 must not believe it set a limit: a non-positive + // value is treated as omitted, and the description has to say so. + assert.match( + repl.parameters.properties.maxDurationSecs?.description ?? "", + /treated as omitted/, + ); + assert.match(repl.parameters.properties.maxMemory?.description ?? "", /treated as omitted/); + }); + + it("documents the session-pool cap in the repl description", async () => { + const repl = (await loadTools()).find((t) => t.name === "repl"); + assert.ok(repl, "repl did not register"); + + // The model is the only party holding an id across calls, so the + // description is where the cap and its one-shot notice must appear. + assert.match(repl.description, /32 live sessions/); + assert.match(repl.description, /oldest session/); + assert.match(repl.description, /\[evicted\] notice/); }); it("documents the cancellation boundary in the repl description (D6)", async () => { diff --git a/test/registry.test.ts b/test/registry.test.ts index dbc368c..28a0d63 100644 --- a/test/registry.test.ts +++ b/test/registry.test.ts @@ -24,6 +24,7 @@ import { createPiBridgeTools } from "../src/bridge.js"; import { createRLMTools } from "../src/rlm_tools.js"; import { createToolStoreTools } from "../src/toolstore.js"; import { SandboxUnavailableError, closeSandboxPool, withSandboxSession } from "../src/pool.js"; +import { MontyComplete } from "@pydantic/monty/node"; // ── Helpers ───────────────────────────────────────────────────── @@ -317,14 +318,33 @@ describe("renderPythonToolRules", () => { assert.ok(rules.includes("datetime")); }); - it("warns that unavailable imports are refused before running", () => { - // Should warn about modules like 'time', 'random' etc. if not importable. - // The truth: with the type checker on, an unavailable import is a static - // `error[unresolved-import]` before any code runs — never a runtime - // ModuleNotFoundError the model could except. + it("says a refused import is a static unresolved-import, not a catchable ModuleNotFoundError", async () => { + // The rules used to promise `ModuleNotFoundError`, which a model acts on + // by writing `try/except ModuleNotFoundError` — code that cannot work: + // the refusal is a typing error before execution, and the exception class + // is itself unresolved to the checker. Prompt text is behaviour (D156), + // so the sentence and the interpreter are measured in the same test. const rules = renderPythonToolRules(["json"]); assert.match(rules, /unresolved-import/); assert.doesNotMatch(rules, /ModuleNotFoundError/); + + const refused = await runInSandbox("import time", { registry: new ToolRegistry() }); + assert.equal(refused.status, "error", JSON.stringify(refused)); + assert.equal(refused.status === "error" ? refused.errorKind : "", "typing"); + assert.match(refused.status === "error" ? refused.error : "", /unresolved-import/); + }); + + it("names every construct that discards the snippet, and the print()-only I/O rule", () => { + // These sentences are the model's only warning that one refused construct + // costs the whole run, and that sys.stdout.write/os.environ pass the + // checker but fail at runtime. + const rules = renderPythonToolRules(["json"]); + assert.match(rules, /yield/); + assert.match(rules, /sys\.stderr\.write/); + assert.match(rules, /os\.environ/); + assert.match(rules, /annotated/); + assert.match(rules, /__name__/); + assert.match(rules, /discards the whole snippet/); }); it("warns that stdlib file access raises PermissionError and points at the tools", () => { @@ -399,6 +419,64 @@ describe("renderPythonToolRules", () => { assert.match(rules, /By default the\s+sandbox has no filesystem/); assert.match(rules, /open\(\)\/os\.listdir\(\)\/pathlib raise PermissionError/); }); + + it("keeps SKILL.md's absent-vs-present split measured, not asserted (D156)", async () => { + // The runtime half of SKILL.md's claim shipped unmeasured; this reads the + // documented names out of the skill and measures every one of them, so + // the list cannot drift from the interpreter. With the checker off a + // resolved name completes (MontyComplete) and an absent one comes back as + // a NameLookupSnapshot, which leaves the session suspended — so each name + // gets a fresh session. A probe that classified everything as present + // fails on the first absent name; `bytearray` is the negative control. + const skill = readFileSync( + join(dirname(fileURLToPath(import.meta.url)), "..", "skills", "repl-simple", "SKILL.md"), + "utf8", + ); + const documented = (marker: string): string[] => { + const line = skill.split("\n").find((l) => l.includes(marker)); + assert.ok(line, `SKILL.md lost its '${marker}' bullet`); + const list = line.slice(line.lastIndexOf(":") + 1); + return [...list.matchAll(/`([^`]+)`/g)].map((m) => m[1]); + }; + const absentDoc = documented("absent at runtime"); + const presentDoc = documented("present** at runtime"); + assert.ok(absentDoc.includes("bytearray"), "the negative control left the absent list"); + + const presentMeasured: string[] = []; + for (const name of [...absentDoc, ...presentDoc]) { + const found = await withSandboxSession({ typeCheck: false }, async (session) => { + const snap = await session.feedStart(name); + return snap instanceof MontyComplete; + }); + if (found) presentMeasured.push(name); + } + assert.deepEqual(presentMeasured, presentDoc, "SKILL.md disagrees with the interpreter"); + }); + + it("measures the lambda-callback claim it makes (D156)", async () => { + // The rule names which call sites reject a callback whose body uses its + // arguments. Measure both halves: a prompt that steers the model off + // working code, or warns about a failure that cannot happen, is a bug in + // this repo — the first version of this bullet did both. + const reducePrint = await runInSandbox( + "import functools\nprint(functools.reduce(lambda a, b: a + b, [1, 2]))", + { registry: new ToolRegistry() }, + ); + assert.equal(reducePrint.status, "error", JSON.stringify(reducePrint)); + assert.match(reducePrint.status === "error" ? reducePrint.error : "", /unsupported-operator/); + + const reduceBare = await runInSandbox( + "import functools\nfunctools.reduce(lambda a, b: a + b, [1, 2])", + { registry: new ToolRegistry() }, + ); + assert.equal(reduceBare.status, "ok", JSON.stringify(reduceBare)); + + const sortedKey = await runInSandbox( + 'print(sorted([(2, "b"), (1, "a")], key=lambda p: p[0]))', + { registry: new ToolRegistry() }, + ); + assert.equal(sortedKey.status, "ok", JSON.stringify(sortedKey)); + }); }); // ── probeImportableModules / probeTypeCheckerGaps ──────────────── diff --git a/test/repl.test.ts b/test/repl.test.ts index 4b08296..a652fd8 100644 --- a/test/repl.test.ts +++ b/test/repl.test.ts @@ -2000,6 +2000,81 @@ describe("ReplRunner — the pool is capped and never drops a pending approval ( cleanup(); } }); + + it("an evicted id is told why it is fresh — once, and only if it was evicted", async () => { + const cwd = makeTempDir(); + const runner = new ReplRunner(cwd, { maxSessions: 2 }); + + try { + await runner.run("v = 1", "keep"); + await runner.run("v = 2", "doomed"); + await runner.run("v", "keep"); // touch: doomed is now the candidate + await runner.run("v = 3", "newcomer"); // over the cap: doomed is evicted + assert.equal(runner.liveSessionCount(), 2); + + const back = await runner.run("1 + 1", "doomed"); + assert.match(back, /\[evicted\]/, `no eviction notice: ${back}`); + assert.match(back, /'doomed'/); + assert.match(back, /oldest session the pool could drop/); + assert.match(back, /2-session cap/); + assert.match(back, /starts fresh/); + assert.match(back, /Raise REPL_MAX_SESSIONS/); + assert.match(back, /\[result\]\n2/, "the notice must ride with the run it explains"); + + const again = await runner.run("2 + 2", "doomed"); + assert.doesNotMatch(again, /\[evicted\]/, "the notice is one-shot"); + + const never = await runner.run("3 + 3", "brand-new"); + assert.doesNotMatch(never, /\[evicted\]/, "a never-created id must not claim eviction"); + } finally { + cleanup(); + } + }); + + it("resume on an evicted id says evicted, not 'no session'", async () => { + const cwd = makeTempDir(); + const runner = new ReplRunner(cwd, { maxSessions: 1 }); + + try { + await runner.run("v = 1", "old"); + await runner.run("v = 2", "new"); // over the cap: old is evicted + + const text = await runner.resume("old"); + assert.match(text, /\[evicted\]/, text); + assert.match(text, /nothing to resume/, text); + assert.doesNotMatch(text, /starts fresh/, "the resume sentence must not promise a fresh run"); + assert.doesNotMatch(text, /No session 'old' exists/); + + // One-shot: the resume consumed the tombstone, so the run that follows + // is not told about the same eviction again. + const after = await runner.run("1 + 1", "old"); + assert.doesNotMatch(after, /\[evicted\]/, `the notice repeated: ${after}`); + } finally { + cleanup(); + } + }); + + it("forgets the oldest tombstone past the bound instead of growing without limit", async () => { + const cwd = makeTempDir(); + const runner = new ReplRunner(cwd, { maxSessions: 1 }); + + try { + // 66 inserts is 65 evictions: one more than EVICTION_TOMBSTONES, so the + // first tombstone must have been forgotten while the newest is still + // there. This is the test that keeps "bounded" true — without it the + // bound branch is never executed. + for (let i = 0; i < 66; i++) await runner.run("1", `s${i}`); + + const newest = await runner.run("1", "s64"); + assert.match(newest, /\[evicted\]/, `the newest tombstone was forgotten: ${newest}`); + + const oldest = await runner.run("1", "s0"); + assert.doesNotMatch(oldest, /\[evicted\]/, "the tombstone map grew past its bound"); + assert.match(oldest, /\[result\]\n1/, "the forgotten id runs as an ordinary fresh session"); + } finally { + cleanup(); + } + }); }); // ── Reset evicts: no hollow entries (#59) ─────────────────────── @@ -2343,7 +2418,13 @@ describe("ReplRunner — resume revalidates after its trust check (#59)", () => releaseCheck(); const out = await resuming; - assert.match(out, /No session 'victim' exists/, `a result for an evicted session: ${out}`); + // The eviction message, not the generic one: the pool dropping the + // session is the reason there is nothing to resume, and a tombstone + // exists to say so (#F8). What this test exists for is unchanged — no + // result for a session the pool no longer holds. + assert.match(out, /\[evicted\]/, `a result for an evicted session: ${out}`); + assert.match(out, /nothing to resume/, out); + assert.doesNotMatch(out, /\[result\]/, `a result for an evicted session: ${out}`); assert.equal(runner.liveSessionCount(), 1, "the eviction did not stick"); } finally { target.trustChangeDiscards = original.bind(runner);