Publish LoLBench Harbor tasks from artifact branch
Browse files100 Harbor tasks; seven-column viewer; immutable DockerHub validation manifest; all union verifiers pass.
This view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- README.md+66
- TypeScript_1/README.mdAdded+87
- TypeScript_1/environment/DockerfileAdded+104
- TypeScript_1/environment/docker-compose.yamlAdded+3
- TypeScript_1/environment/lolbench-submitAdded+33
- TypeScript_1/environment/metadata.jsonAdded+22
- TypeScript_1/environment/source_audit.jsonAdded+7
- TypeScript_1/instruction.mdAdded+362
- TypeScript_1/solution/solution.patchAdded+507
- TypeScript_1/solution/solve.shAdded+7
- TypeScript_1/task.tomlAdded+60
- TypeScript_1/tests/docker-compose.yamlAdded+16
- TypeScript_1/tests/private/eval_tests.patchAdded
- TypeScript_1/tests/private/eval_tests_aug.patchAdded+185
- TypeScript_1/tests/private/f2p.txtAdded+13
- TypeScript_1/tests/private/f2p_aug.txtAdded+3
- TypeScript_1/tests/private/p2p.txtAdded+50
- TypeScript_1/tests/private/p2p_aug.txtAdded+2
- TypeScript_1/tests/private/run_tests.shAdded+339
- TypeScript_1/tests/private/spec.jsonAdded+507
- TypeScript_1/tests/report_to_reward.pyAdded+73
- TypeScript_1/tests/test.shAdded+43
- TypeScript_2/README.mdAdded+90
- TypeScript_2/environment/DockerfileAdded+95
- TypeScript_2/environment/docker-compose.yamlAdded+3
- TypeScript_2/environment/lolbench-submitAdded+33
- TypeScript_2/environment/metadata.jsonAdded+22
- TypeScript_2/environment/runtime_source_guard.pyAdded+353
- TypeScript_2/environment/runtime_source_guard_entrypoint.cAdded+62
- TypeScript_2/environment/source_audit.jsonAdded+7
- TypeScript_2/instruction.mdAdded+1824
- TypeScript_2/solution/solution.patchAdded
- TypeScript_2/solution/solve.shAdded+7
- TypeScript_2/task.tomlAdded+60
- TypeScript_2/tests/docker-compose.yamlAdded+16
- TypeScript_2/tests/private/eval_tests.patchAdded
- TypeScript_2/tests/private/eval_tests_aug.patchAdded+255
- TypeScript_2/tests/private/f2p.txtAdded+16
- TypeScript_2/tests/private/f2p_aug.txtAdded+2
- TypeScript_2/tests/private/p2p.txtAdded+50
- TypeScript_2/tests/private/p2p_aug.txtAdded+2
- TypeScript_2/tests/private/run_tests.shAdded+337
- TypeScript_2/tests/private/spec.jsonAdded+325
- TypeScript_2/tests/report_to_reward.pyAdded+73
- TypeScript_2/tests/test.shAdded+43
- TypeScript_3/README.mdAdded+87
- TypeScript_3/environment/DockerfileAdded+86
- TypeScript_3/environment/docker-compose.yamlAdded+3
- TypeScript_3/environment/lolbench-submitAdded+33
- TypeScript_3/environment/metadata.jsonAdded+22
123---license: apache-2.0---123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869---license: apache-2.0task_categories:- text-generationlanguage:- entags:- code-generation- software-engineering- benchmark- long-horizon- harborsize_categories:- n<1Kconfigs:- config_name: defaultdata_files:- split: trainpath: tasks_overview.jsonl---# LoLBenchLoLBench (Long-horizon Tasks on Large Software Projects) evaluates coding agents on complex, repository-level software engineering tasks. This dataset export contains only the 100 Harbor-format tasks prepared from the repository's `artifact` branch.The source task directories are included at the dataset root. The `tasks_overview.jsonl` file provides a compact dataset-viewer representation similar to RoadmapBench.## Dataset viewer schema| Column | Description || --- | --- || `task_id` | Harbor task identifier. || `language` | Normalized implementation language or language combination. || `domain` | Broad software-project domain. || `instruction` | Complete contents of the task's `instruction.md`. || `f2p` | Overall fail-to-pass suite as test selectors only. || `p2p` | Overall pass-to-pass suite as test selectors only. || `solution` | Complete contents of `solution/solution.patch`. |`f2p` and `p2p` use the canonical overall suite: the original selectors followed by the augmented selectors in execution order. Repeated selectors are retained because they are part of the executed suite. These columns do not contain test implementations or test patch contents.## Task layoutEach task directory contains the Harbor task definition and its associated assets:```text<task_id>/├── environment/├── solution/│ └── solution.patch├── tests/├── instruction.md├── README.md└── task.toml```The task metadata records the upstream repository, base commit, target merge/solution commit, and published container image. The canonical verifier mode is `union`, which evaluates the overall original-plus-augmented test suites represented in the viewer.## Provenance and validationThis export was prepared from source commit `679d4983b9aa131cd79b9abfb2cdca30d4eb0329` on the `artifact` branch. During export, task identifiers, repository metadata, full base and target commit SHAs, source-audit metadata, selector types, recorded asset checksums, and required task files were checked for consistency. All 200 declared base and merge commit references resolved against their upstream GitHub repositories.On 2026-09-19, the current `linux/amd64` image for every task was pulled from Docker Hub and the ground-truth `solution/solution.patch` was evaluated in canonical `union` mode. All 100/100 tasks resolved with reward `1.0`: F2P passed 2,234/2,234 selectors and P2P passed 5,660/5,660 selectors.The [`validation/dockerhub_validation.json`](validation/dockerhub_validation.json) manifest records the immutable Docker Hub index and `linux/amd64` platform digest used for every task, together with its verifier totals and validation timestamp. It is validation metadata only and is intentionally excluded from the dataset-viewer configuration. In the 11 task specifications that exposed Docker Hub metadata at the top level, those fields describe the current `lolbench-linux` image; nested, dated `harbor_validation_summary` objects remain unchanged as historical arm64 validation evidence.Export-time consistency corrections expanded two abbreviated Kubernetes target SHAs, synchronized seven solution-patch checksums and nine other packaged test-asset checksums, and replaced the stale `cpython_5` base reference with the actual parent of its declared squash merge. The corrected `cpython_5` solution patch was also checked to apply cleanly to that base. JDK verifier launchers were made architecture-aware for both `x86_64` and `aarch64`, and all packaged verifier shell scripts passed syntax checks.LoLBench-authored benchmark metadata and tooling are released under Apache-2.0. Individual upstream projects and incorporated materials remain subject to their respective licenses.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# LoLBench Harbor Task: TypeScript_1
This is a Harbor-format LoLBench task generated from `TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827`.
Selected source instance:
- Harbor ID: `TypeScript_1`- PR: `microsoft/TypeScript#46827`- Base commit: `07157914eb26a6e9abdcda7255c4094c9efff4cd`- Test modes: `orig, aug, union`- Default/canonical mode: `union`- Harbor image: `smartdub26/lolbench-linux:TypeScript_1-1.0.0`- Docker Hub image: `smartdub26/lolbench-linux:TypeScript_1-1.0.0`
## Image Setup
Prefer the published Docker Hub image when it is available. Harbor refers tothe image as `smartdub26/lolbench-linux:TypeScript_1-1.0.0`, so Docker can pull itdirectly when it is not present locally:
```bashdocker pull smartdub26/lolbench-linux:TypeScript_1-1.0.0```
Only if the Docker Hub image is unavailable, build the single task imagelocally:
```bashdocker build -t lolbench/typescript_1:1.0.0 harbor_tasks/TypeScript_1/environmentdocker tag lolbench/typescript_1:1.0.0 smartdub26/lolbench-linux:TypeScript_1-1.0.0```
The image contains the processed source tree at the base commit under`/workspace/typescript`. Harbor must not mount a host source checkoutfor the agent.
## Run an Agent
```bash.harbor-venv/bin/harbor run \ -p harbor_tasks/TypeScript_1 \ -a codex \ -m "<model>" \ --job-name TypeScript_1_agent_union \ --jobs-dir harbor_runs/TypeScript_1 \ --no-delete \ --n-concurrent 1 \ --ve LOLBENCH_SUITE=union```
After implementing the requirement, the agent must clean any test-file editsand run:
```bashlolbench-submit```
## Evaluate a Patch
Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, thetask defaults to `union`.
```bashPATCH="$(pwd)/path/to/solution.patch"
.harbor-venv/bin/harbor run \ -p harbor_tasks/TypeScript_1 \ -a oracle \ --job-name TypeScript_1_eval_union \ --jobs-dir harbor_runs/TypeScript_1 \ --no-delete \ --n-concurrent 1 \ --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ --ve LOLBENCH_SUITE=union```
Outputs:
```bashfind harbor_runs/TypeScript_1/TypeScript_1_eval_union -path '*/verifier/agent_report.json' -printfind harbor_runs/TypeScript_1/TypeScript_1_eval_union -path '*/verifier/reward.json' -print```
`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts`tests/`, `tests/private/`, and `solution/` into the separate verifiercontainer; none of those paths are mounted into the agent container.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104# LoLBench eval image: TypeScript PR-46827 (satisfies operator)# Requirement: https://github.com/microsoft/TypeScript/issues/47920# base_commit: 07157914eb26a6e9abdcda7255c4094c9efff4cd# (parent of the squash-merge 164dddc4 on main)## Agent-facing contract (the agent only ever produces a solution.patch;# the evaluator runs the container):## docker run --rm \# --network=none \# -v $(pwd)/solution.patch:/in/solution.patch:ro \# -v $(pwd)/out:/out \# lolbench/apache-ts-pr-46827:1## Layered build:# layer 1: ubuntu:22.04# layer 2: lolbench/typescript-base:1 (Node 16 + git + build deps)# layer 3: THIS image (TS @ base + npm install + gulp local)
ARG BASE_IMAGE=lolbench/typescript-base:1FROM ${BASE_IMAGE}
ARG BASE_COMMIT=07157914eb26a6e9abdcda7255c4094c9efff4cd
RUN mkdir -p /opt/lolbench/private /in /out /workspace
WORKDIR /workspaceRUN git init typescript && \ cd typescript && \ git remote add origin https://github.com/microsoft/TypeScript.git && \ git fetch --no-tags origin ${BASE_COMMIT} && \ git checkout ${BASE_COMMIT} && \ git ls-files -z > /tmp/typescript-base-files && \ git config user.email lolbench@local && \ git config user.name lolbench && \ if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ fi && \ git tag -f base && git tag -f lolbench-base && \ git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ while read ref; do \ case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ done && \ ( git remote remove origin 2>/dev/null || true ) && \ rm -f .git/FETCH_HEAD && \ git reflog expire --expire=now --all && \ git repack -Ad && \ git prune --expire=now && \ rm /tmp/typescript-base-files && \ git config --global --add safe.directory /workspace/typescript
# ---- Install deps + build TypeScript from the base sources.# The runtests harness needs both built/local/* (the compiled tsc and# test runners) AND node_modules/* installed. npm install is ~3 min,# gulp local is ~5 min, gulp tests is ~2 min on a 4-core host.RUN cd /workspace/typescript && \ npm install --no-progress --no-fund --no-audit && \ npx gulp local && \ npx gulp tests
# ---- Eval bundle ------------------------------------------------------
# Harbor runtime adapter: keep the image public/agent-safe.RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fiCOPY metadata.json /opt/lolbench/metadata.jsonCOPY lolbench-submit /usr/local/bin/lolbench-submitRUN chmod +x /usr/local/bin/lolbench-submit && \ git config --global --add safe.directory /workspace/typescript && \ if [ -d /workspace/typescript/.git ]; then \ cd /workspace/typescript && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ else \ : > /opt/lolbench/base_untracked.txt; \ fi && \ chown -R agent:agent /workspace/typescript /logsENV HOME=/home/agent# Local-reference hardening: retain only the approved base history.RUN git config --system --add safe.directory /workspace/typescript && \ cd /workspace/typescript && \ git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ while read ref; do \ case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ done && \ ( git remote remove origin 2>/dev/null || true ) && \ rm -f .git/FETCH_HEAD && \ git reflog expire --expire=now --all && \ git repack -Ad && \ git prune --expire=now && \ unreachable=$(git fsck --unreachable --no-reflogs) && \ test -z "$unreachable" && \ chown -R agent:agent .git# Keep npm executable but remove cached/global copies of TypeScript sources.RUN rm -rf /root/.npm /home/agent/.npm && \ rm -f /usr/local/bin/tsc /usr/local/bin/tsserver /usr/bin/tsc /usr/bin/tsserver && \ for p in /usr/local/lib/node_modules /usr/lib/node_modules; do \ if [ -d "$p" ]; then \ find "$p" -mindepth 1 -maxdepth 1 -type d -iname typescript -exec rm -rf '{}' +; \ chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; \ fi; \ doneUSER agentWORKDIR /workspace/typescriptENV LOLBENCH_INSTANCE_ID=TypeScript_1ENV LOLBENCH_SOURCE_SLUG=TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827123services: main: pull_policy: missing123456789101112131415161718192021222324252627282930313233#!/usr/bin/env bashset -euo pipefailexport LC_ALL=C
repo=${1:-$PWD}out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch}
mkdir -p "$(dirname "$out")"cd "$repo"
baseline=/opt/lolbench/base_untracked.txtcurrent=$(mktemp)new_files=$(mktemp)trap 'rm -f "$current" "$new_files"' EXIT
git ls-files --others --exclude-standard | sort > "$current"if [ -f "$baseline" ]; then comm -13 "$baseline" "$current" > "$new_files"else cp "$current" "$new_files"fi
if [ -s "$new_files" ]; then xargs -r git add -N -- < "$new_files"fi
git diff --binary > "$out"
if [ ! -s "$out" ]; then echo "warning: wrote an empty solution patch to $out" >&2else echo "wrote solution patch to $out"fi12345678910111213141516171819202122{ "instance_id": "TypeScript_1", "source_instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", "source_slug": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", "docker_slug": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_1-1.0.0", "project": "TypeScript", "repo": "microsoft/TypeScript", "requirement_doc": "https://github.com/microsoft/TypeScript/issues/47920", "pr_link": "https://github.com/microsoft/TypeScript/pull/46827", "base_commit": "07157914eb26a6e9abdcda7255c4094c9efff4cd", "merge_commit": "a73f1c7ce4b97bf13e6c3f2341412b0216d92933", "source_history_policy": "ancestors-only", "lolbench_test_modes": [ "orig", "aug", "union" ], "default_lolbench_suite": "union", "canonical_lolbench_suite": "union", "augmentation_available": true}1234567{ "source_policy": "dockerfile_fetch_pruned_ancestor_history", "local_reference_policy": "auxiliary_sources_removed_execute_only", "base_commit": "07157914eb26a6e9abdcda7255c4094c9efff4cd", "repo": "microsoft/TypeScript", "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, asserts that git fsck finds no unreachable object, removes auxiliary reference sources, and makes remaining auxiliary toolchains root-owned and non-enumerable to the agent."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362You are working in `/workspace/typescript`, a source tree checked out atthe base commit for this task. Implement the requested behavior in the sourcetree, then run:
```bashlolbench-submit```
Do not stop after editing files, running tests, or describing the solution. Thetask is complete only when `lolbench-submit` has created`/logs/artifacts/solution.patch`. If that file does not exist, continueworking and run `lolbench-submit` again.
That command writes your implementation diff to`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifierwill grade. Before running `lolbench-submit`, clean or revert any test filesyou created or modified; test files must not be included in the final`solution.patch`.
This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources.
Now please implement the following requirements in the source tree:
---
# "satisfies" operator to ensure an expression matches some type (feedback reset)
# Feature Update - February 2022
This is a feedback reset for #7481 to get a fresh start and clarify where we are with this feature. I really thought this was going to be simpler, but it's turned out to be a bit of a rat's nest!
Let's start with what kind of scenarios we think need to be addressed.
## Scenario Candidates
First, here's a review of scenarios I've collected from reading the linked issue and its many duplicates. **Please post if you have other scenarios that seem relevant**. I'll go into it later, but *not all these scenarios can be satisfied at once* for reasons that will hopefully become obvious.
### Safe Upcast
Frequently in places where control flow analysis hits some limitation (hi #9998), it's desirable to "undo" the specificity of an initializer. A good example would be```tslet a = false;upd();if (a === true) {// ^^^ error, true and false have no overlap // ...}function upd() { if (someCondition) a = true;}```The canonical recommendation is to type-assert the initializer:```tslet a = false as boolean;```but there's limited type safety here since you could accidently downcast without realizing it:```tstype Animal = { kind: "cat", meows: true } | { kind: "dog", barks: true };let p = { kind: "cat" } as Animal; // Missing meows!upd();if (p.kind === "dog") {
} else { p.meows; // Reported 'true', actually 'undefined'}function upd() { if (Math.random() > 0.5) p = { kind: "dog", barks: true };}```
The safest workaround is to have a dummy function, `function up<T>(arg: T): T`:```tslet a = up<boolean>(true);```which is unfortunate due to having unnecessary runtime impact.
Instead, we would presumably write```tslet p = { kind: "cat", meows: true } satisfies Animal;```
### Property Name Constraining
We might want to make a lookup table where the property keys must come from some predefined subset, but not lose type information about what each property's value was:```tstype Keys = 'a' | 'b' | 'c' | 'd';
const p = { a: 0, b: "hello", x: 8 // Should error, 'x' isn't in 'Keys'};
// Should be OK -- retain info that a is number and b is stringlet a = p.a.toFixed();let b = p.b.substr(1);// Should error even though 'd' is in 'Keys'let d = p.d;```There is no obvious workaround here today.
Instead, we would presumably write```tsconst p = { a: 0, b: "hello", x: 8 // Should error, 'x' isn't in 'Keys'} satisfies Partial<Record<Keys, unknown>>;// using 'Partial' to indicate it's OK 'd' is missing```
### Property Name Fulfillment
Same as Property Name Constraining, except we might want to ensure that we get *all* of the keys:
```tstype Keys = 'a' | 'b' | 'c' | 'd';
const p = { a: 0, b: "hello", c: true // Should error because 'd' is missing};// Should be OKconst t: boolean = p.c;```
The closest available workaround is:```tsconst dummy: Record<Keys, unknown> = p;```but this assignment a) has runtime impact and b) will not detect excess properties.
Instead, we would presumably write```tsconst p = { a: 0, b: "hello", c: true // will error because 'd' is missing} satisfies Record<Keys, unknown>;```
### Property Value Conformance
This is the flipside of Property Name Constraining - we might want to make sure that all *property values* in an object conform to some type, but still keep record of which keys are present:```tstype Facts = { [key: string]: boolean };declare function checkTruths(x: Facts): void;declare function checkM(x: { m: boolean }): void;const x = { m: true};
// Should be OKcheckTruths(x);// Should be OKfn(x);// Should fail under --noIndexSignaturePropertyAccessconsole.log(x.z);// Should be OK under --noUncheckedIndexedAccessconst m: boolean = x.m;
// Should be 'm'type M = keyof typeof x;
// Should be able to detect a failure hereconst x2 = { m: true, s: "false"};```
Another example```tsexport type Color = { r: number, g: number, b: number };
// All of these should be Colors, but I only use some of them here.export const Palette = { white: { r: 255, g: 255, b: 255}, black: { r: 0, g: 0, d: 0}, // <- oops! 'd' in place of 'b' blue: { r: 0, g: 0, b: 255 },};```
Here, we would presumably write```tsconst Palette = { white: { r: 255, g: 255, b: 255}, black: { r: 0, g: 0, d: 0}, // <- error is now detected blue: { r: 0, g: 0, b: 255 },} satisfies Record<string, Color>;```
### Ensure Interface Implementation
We might want to leverage type inference, but still check that something conforms to an interface and use that interface to provide contextual typing:```tstype Movable = { move(distance: number): void;};
const car = { start() { }, move(d) { // d should be number }, stop() { }};```
Here, we would presumably write```tsconst car = { start() { }, move(d) { // d: number }, stop() { }} satisfies Moveable;```
### Optional Member Conformance
We might want to initialize a value conforming to some weakly-typed interface:```tstype Point2d = { x: number, y: number };// Undesirable behavior today with type annotationconst a: Partial<Point2d> = { x: 10 };// Errors, but should be OK -- we know x is thereconsole.log(a.x.toFixed());// OK, but should be an error -- we know y is missinglet p = a.y;```
### Optional Member Addition
Conversely, we might want to safely initialize a variable according to some type but retain information about the members which aren't present:```tstype Point2d = { x: number, y: number };const a: Partial<Point2d> = { x: 10 };// Should be OKa.x.toFixed();// Should be OK, y is present, just not initializeda.y = 3;```
### Contextual Typing
TypeScript has a process called *contextual typing* in which expressions which would otherwise not have an inferrable type can get an inferred type from context:```ts// a: implicit anyconst f1 = a => { };
// a: stringconst f2: (s: string) => void = a => { };```
In all of the above scenarios, contextual typing would always be appropriate. For example, in *Property Value Conformance*```tstype Predicates = { [s: string]: (n: number) => boolean };
const p: Predicates = { isEven: n => n % 2 === 0, isOdd: n => n % 2 === 1};```Contextually providing the `n` parameters a `number` type is clearly desirable. In most other places than parameters, the contextual typing of an expression is not directly observable except insofar as normally-disallowed assignments become allowable.
## Desired Behavior Rundown
There are three plausible contenders for what to infer for the type of an `e satisfies T` expression: * `typeof e` * `T` * `T & typeof e`
*SATA: Same As Type Annotation - `const v = e satisfies T` would do the same as `const v: T = e`, thus no additional value is provided
|Scenario|`T`|`typeof e`|`T & typeof e`||--------|---|----------|--------------||Safe Upcast|✔|❌ (undoes the upcasting)|❌ (undoes the upcasting)||Property Name Constraining|❌ (SATA)|✔|✔||Property Name Fulfillment|❌ (SATA)|✔|✔||Ensure Interface Implementation|❌ (SATA)|✔|✔||Optional Member Conformance|❌ (SATA)|✔|❌ (members appear when not desired)||Optional Member Addition|❌ (SATA)|❌ (members do not appear when desired)|✔||Contextual Typing|✔|✔|✔|
### Discussion
Given the value of the other scenarios, I think *safe upcast* needs to be discarded. One could imagine other solutions to this problem, e.g. marking a particular variable as "volatile" such that narrowings no longer apply to it, or simply by having better side-effect tracking.
### Excess Properties
A sidenote here on excess properties. Consider this case:```tstype Point = { x: number, y: number};const origin = { x: 0, y: 0, z: 0 // OK or error?} satisifes Point;```
Is `z` an excess property?
One argument says yes, because in other positions where that object literal was used where a `Point` was expected, it would be. Additionally, if we want to detect typos (as in the *property name constraining* scenario), then detecting excess properties is mandatory.
The other argument says no, because the point of excess property checks is to detect properties which are "lost" due to not having their presence captured by the type system, and the design of the `satisfies` operator is specifically for scenarios where the ultimate type of all properties *is* captured somewhere.
I think on balance, the "yes" argument is stronger. If we don't flag excess properties, then the *property name constraining* scenario can't be made to work at all. In places where excess properties are expected, `e satisfies (T & Record<string, unknown>)` can be written instead.
However, under this solution, producing the expression type `T & typeof e` becomes very undesirable:```tstype Point2d = { x: number, y: number };const a = { x: 10, z: 0 } satisfies Partial<Point2d> & Record<string, unknown>;// Arbitrary writes allowed (super bad)a.blah = 10;```
Side note: It's tempting to say that properties aren't excess if all of the satisfied type's properties are matched. I don't think this is satisfactory because it doesn't really clearly define what would happen with the asserted-to type is `Partial`, which is likely common:```tstype Keys = 'a' | 'b' | 'c';// Property 'd' might be intentional excess *or* a typo of e.g. 'b'const v = { a: 0, d: 0 } satisfies Partial<Record<Keys, number>>;```
Producing `typeof e` then leads to another problem...
### The Empty Array Problem
Under `--strict` (specifically `strictNullChecks && noImplicitAny`), empty arrays in positions where they can't be Evolving Arrays get the type `never[]`. This leads to some somewhat annoying behavior today:```tslet m = { value: [] };// Error, can't assign 'number' to 'never'm.value.push(3);```
The `satisfies` operator might be thought to fix this:```tstype BoxOfArray<T> = { value: T[] };let m = { value: [] } satisfies BoxOfArray<number>// OK, right? I just said it was OK?m.value.push(3);```
However, under current semantics (including `m: typeof e`), this still doesn't work, because the type of the array is still `never[]`.
It seems like this can be fixed with a targeted change to empty arrays, which I've prototyped at #47898. It's possible there are unintended downstream consequences of this (changes like this can often foul up generic inference in ways that aren't obvious), but it seems to be OK for now.
## TL;DR
It seems like the best place we could land is: * Contextually type empty arrays * Disallow excess properties (unless you write `T & Record<string, unknown>`) * Use `typeof e` as the expression type instead of `T` or `T & typeof e`
Does this seem right? What did I miss?123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507diff --git a/src/compiler/checker.ts b/src/compiler/checker.tsindex 0999b8b4eb..321592bcd4 100644--- a/src/compiler/checker.ts+++ b/src/compiler/checker.ts@@ -27506,6 +27506,8 @@ namespace ts { }
case SyntaxKind.NonNullExpression:
return getContextualType(parent as NonNullExpression, contextFlags);
+ case SyntaxKind.SatisfiesExpression:
+ return getTypeFromTypeNode((parent as SatisfiesExpression).type);
case SyntaxKind.ExportAssignment:
return tryGetTypeFromEffectiveTypeNode(parent as ExportAssignment);
case SyntaxKind.JsxExpression:
@@ -32442,6 +32444,20 @@ namespace ts { }
}
+ function checkSatisfiesExpression(node: SatisfiesExpression) {
+ checkSourceElement(node.type);
+
+ const targetType = getTypeFromTypeNode(node.type);
+ if (isErrorType(targetType)) {
+ return targetType;
+ }
+
+ const exprType = checkExpression(node.expression);
+ checkTypeAssignableToAndOptionallyElaborate(exprType, targetType, node.type, node.expression, Diagnostics.Type_0_does_not_satisfy_the_expected_type_1);
+
+ return exprType;
+ }
+
function checkMetaProperty(node: MetaProperty): Type {
checkGrammarMetaProperty(node);
@@ -35235,6 +35251,8 @@ namespace ts { return checkNonNullAssertion(node as NonNullExpression);
case SyntaxKind.ExpressionWithTypeArguments:
return checkExpressionWithTypeArguments(node as ExpressionWithTypeArguments);
+ case SyntaxKind.SatisfiesExpression:
+ return checkSatisfiesExpression(node as SatisfiesExpression);
case SyntaxKind.MetaProperty:
return checkMetaProperty(node as MetaProperty);
case SyntaxKind.DeleteExpression:
diff --git a/src/compiler/diagnosticMessages.json b/src/compiler/diagnosticMessages.jsonindex e1f62fe842..2656c48383 100644--- a/src/compiler/diagnosticMessages.json+++ b/src/compiler/diagnosticMessages.json@@ -1100,7 +1100,7 @@ "category": "Error",
"code": 1359
},
- "Class constructor may not be a generator.": {
+ "Type '{0}' does not satisfy the expected type '{1}'.": {
"category": "Error",
"code": 1360
},
@@ -1132,6 +1132,10 @@ "category": "Message",
"code": 1367
},
+ "Class constructor may not be a generator.": {
+ "category": "Error",
+ "code": 1368
+ },
"Did you mean '{0}'?": {
"category": "Message",
"code": 1369
@@ -6376,6 +6380,10 @@ "category": "Error",
"code": 8036
},
+ "Type satisfaction expressions can only be used in TypeScript files.": {
+ "category": "Error",
+ "code": 8037
+ },
"Declaration emit for this file requires using private name '{0}'. An explicit type annotation may unblock declaration emit.": {
"category": "Error",
diff --git a/src/compiler/emitter.ts b/src/compiler/emitter.tsindex d3008431ab..4e571c49a8 100644--- a/src/compiler/emitter.ts+++ b/src/compiler/emitter.ts@@ -1763,6 +1763,8 @@ namespace ts { return emitNonNullExpression(node as NonNullExpression);
case SyntaxKind.ExpressionWithTypeArguments:
return emitExpressionWithTypeArguments(node as ExpressionWithTypeArguments);
+ case SyntaxKind.SatisfiesExpression:
+ return emitSatisfiesExpression(node as SatisfiesExpression);
case SyntaxKind.MetaProperty:
return emitMetaProperty(node as MetaProperty);
case SyntaxKind.SyntheticExpression:
@@ -2846,6 +2848,16 @@ namespace ts { writeOperator("!");
}
+ function emitSatisfiesExpression(node: SatisfiesExpression) {
+ emitExpression(node.expression, /*parenthesizerRules*/ undefined);
+ if (node.type) {
+ writeSpace();
+ writeKeyword("satisfies");
+ writeSpace();
+ emit(node.type);
+ }
+ }
+
function emitMetaProperty(node: MetaProperty) {
writeToken(node.keywordToken, node.pos, writePunctuation);
writePunctuation(".");
diff --git a/src/compiler/factory/nodeFactory.ts b/src/compiler/factory/nodeFactory.tsindex 399dfd9d64..f072083e15 100644--- a/src/compiler/factory/nodeFactory.ts+++ b/src/compiler/factory/nodeFactory.ts@@ -222,6 +222,8 @@ namespace ts { updateAsExpression,
createNonNullExpression,
updateNonNullExpression,
+ createSatisfiesExpression,
+ updateSatisfiesExpression,
createNonNullChain,
updateNonNullChain,
createMetaProperty,
@@ -3142,6 +3144,26 @@ namespace ts { : node;
}
+ // @api
+ function createSatisfiesExpression(expression: Expression, type: TypeNode) {
+ const node = createBaseExpression<SatisfiesExpression>(SyntaxKind.SatisfiesExpression);
+ node.expression = expression;
+ node.type = type;
+ node.transformFlags |=
+ propagateChildFlags(node.expression) |
+ propagateChildFlags(node.type) |
+ TransformFlags.ContainsTypeScript;
+ return node;
+ }
+
+ // @api
+ function updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode) {
+ return node.expression !== expression
+ || node.type !== type
+ ? update(createSatisfiesExpression(expression, type), node)
+ : node;
+ }
+
// @api
function createNonNullChain(expression: Expression) {
const node = createBaseExpression<NonNullChain>(SyntaxKind.NonNullExpression);
@@ -5730,6 +5752,7 @@ namespace ts { case SyntaxKind.ParenthesizedExpression: return updateParenthesizedExpression(outerExpression, expression);
case SyntaxKind.TypeAssertionExpression: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
case SyntaxKind.AsExpression: return updateAsExpression(outerExpression, expression, outerExpression.type);
+ case SyntaxKind.SatisfiesExpression: return updateSatisfiesExpression(outerExpression, expression, outerExpression.type);
case SyntaxKind.NonNullExpression: return updateNonNullExpression(outerExpression, expression);
case SyntaxKind.PartiallyEmittedExpression: return updatePartiallyEmittedExpression(outerExpression, expression);
}
@@ -6465,6 +6488,7 @@ namespace ts { case SyntaxKind.ArrayBindingPattern:
return TransformFlags.BindingPatternExcludes;
case SyntaxKind.TypeAssertionExpression:
+ case SyntaxKind.SatisfiesExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.PartiallyEmittedExpression:
case SyntaxKind.ParenthesizedExpression:
diff --git a/src/compiler/factory/nodeTests.ts b/src/compiler/factory/nodeTests.tsindex 903dea149a..f44c913640 100644--- a/src/compiler/factory/nodeTests.ts+++ b/src/compiler/factory/nodeTests.ts@@ -438,6 +438,10 @@ namespace ts { return node.kind === SyntaxKind.AsExpression;
}
+ export function isSatisfiesExpression(node: Node): node is SatisfiesExpression {
+ return node.kind === SyntaxKind.SatisfiesExpression;
+ }
+
export function isNonNullExpression(node: Node): node is NonNullExpression {
return node.kind === SyntaxKind.NonNullExpression;
}
diff --git a/src/compiler/factory/utilities.ts b/src/compiler/factory/utilities.tsindex 9fbbdb165d..7cb707a90a 100644--- a/src/compiler/factory/utilities.ts+++ b/src/compiler/factory/utilities.ts@@ -437,6 +437,7 @@ namespace ts { return (kinds & OuterExpressionKinds.Parentheses) !== 0;
case SyntaxKind.TypeAssertionExpression:
case SyntaxKind.AsExpression:
+ case SyntaxKind.SatisfiesExpression:
return (kinds & OuterExpressionKinds.TypeAssertions) !== 0;
case SyntaxKind.NonNullExpression:
return (kinds & OuterExpressionKinds.NonNullAssertions) !== 0;
diff --git a/src/compiler/parser.ts b/src/compiler/parser.tsindex 93939b6f4f..faab2b0620 100644--- a/src/compiler/parser.ts+++ b/src/compiler/parser.ts@@ -393,6 +393,9 @@ namespace ts { [SyntaxKind.NonNullExpression]: function forEachChildInNonNullExpression<T>(node: NonNullExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray<Node>) => T | undefined): T | undefined {
return visitNode(cbNode, node.expression);
},
+ [SyntaxKind.SatisfiesExpression]: function forEachChildInSatisfiesExpression<T>(node: SatisfiesExpression, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray<Node>) => T | undefined): T | undefined {
+ return visitNode(cbNode, node.expression) || visitNode(cbNode, node.type);
+ },
[SyntaxKind.MetaProperty]: function forEachChildInMetaProperty<T>(node: MetaProperty, cbNode: (node: Node) => T | undefined, _cbNodes?: (nodes: NodeArray<Node>) => T | undefined): T | undefined {
return visitNode(cbNode, node.name);
},
@@ -841,7 +844,6 @@ namespace ts { if (node === undefined || node.kind <= SyntaxKind.LastToken) {
return;
}
-
const fn = (forEachChildTable as Record<SyntaxKind, ForEachChildFunction<any>>)[node.kind];
return fn === undefined ? undefined : fn(node, cbNode, cbNodes);
}
@@ -5109,7 +5111,7 @@ namespace ts { break;
}
- if (token() === SyntaxKind.AsKeyword) {
+ if (token() === SyntaxKind.AsKeyword || token() === SyntaxKind.SatisfiesKeyword) {
// Make sure we *do* perform ASI for constructs like this:
// var x = foo
// as (Bar)
@@ -5119,8 +5121,10 @@ namespace ts { break;
}
else {
+ const keywordKind = token();
nextToken();
- leftOperand = makeAsExpression(leftOperand, parseType());
+ leftOperand = keywordKind === SyntaxKind.SatisfiesKeyword ? makeSatisfiesExpression(leftOperand, parseType()) :
+ makeAsExpression(leftOperand, parseType());
}
}
else {
@@ -5139,6 +5143,10 @@ namespace ts { return getBinaryOperatorPrecedence(token()) > 0;
}
+ function makeSatisfiesExpression(left: Expression, right: TypeNode): SatisfiesExpression {
+ return finishNode(factory.createSatisfiesExpression(left, right), left.pos);
+ }
+
function makeBinaryExpression(left: Expression, operatorToken: BinaryOperatorToken, right: Expression, pos: number): BinaryExpression {
return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos);
}
diff --git a/src/compiler/program.ts b/src/compiler/program.tsindex e7c0f363ea..2c71fde33d 100644--- a/src/compiler/program.ts+++ b/src/compiler/program.ts@@ -2372,6 +2372,9 @@ namespace ts { case SyntaxKind.AsExpression:
diagnostics.push(createDiagnosticForNode((node as AsExpression).type, Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
return "skip";
+ case SyntaxKind.SatisfiesExpression:
+ diagnostics.push(createDiagnosticForNode((node as SatisfiesExpression).type, Diagnostics.Type_satisfaction_expressions_can_only_be_used_in_TypeScript_files));
+ return "skip";
case SyntaxKind.TypeAssertionExpression:
Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
}
diff --git a/src/compiler/scanner.ts b/src/compiler/scanner.tsindex 107ff3a143..05ae6268d7 100644--- a/src/compiler/scanner.ts+++ b/src/compiler/scanner.ts@@ -136,6 +136,7 @@ namespace ts { require: SyntaxKind.RequireKeyword,
global: SyntaxKind.GlobalKeyword,
return: SyntaxKind.ReturnKeyword,
+ satisfies: SyntaxKind.SatisfiesKeyword,
set: SyntaxKind.SetKeyword,
static: SyntaxKind.StaticKeyword,
string: SyntaxKind.StringKeyword,
diff --git a/src/compiler/transformers/ts.ts b/src/compiler/transformers/ts.tsindex 61b982d7f2..0f27255590 100644--- a/src/compiler/transformers/ts.ts+++ b/src/compiler/transformers/ts.ts@@ -529,6 +529,9 @@ namespace ts { // TypeScript type assertions are removed, but their subtrees are preserved.
return visitAssertionExpression(node as AssertionExpression);
+ case SyntaxKind.SatisfiesExpression:
+ return visitSatisfiesExpression(node as SatisfiesExpression);
+
case SyntaxKind.CallExpression:
return visitCallExpression(node as CallExpression);
@@ -1421,6 +1424,11 @@ namespace ts { return factory.createPartiallyEmittedExpression(expression, node);
}
+ function visitSatisfiesExpression(node: SatisfiesExpression): Expression {
+ const expression = visitNode(node.expression, visitor, isExpression);
+ return factory.createPartiallyEmittedExpression(expression, node);
+ }
+
function visitCallExpression(node: CallExpression) {
return factory.updateCallExpression(
node,
diff --git a/src/compiler/types.ts b/src/compiler/types.tsindex 73fefe7637..31bdb48f75 100644--- a/src/compiler/types.ts+++ b/src/compiler/types.ts@@ -181,6 +181,7 @@ namespace ts { RequireKeyword,
NumberKeyword,
ObjectKeyword,
+ SatisfiesKeyword,
SetKeyword,
StringKeyword,
SymbolKeyword,
@@ -274,6 +275,7 @@ namespace ts { NonNullExpression,
MetaProperty,
SyntheticExpression,
+ SatisfiesExpression,
// Misc
TemplateSpan,
@@ -607,6 +609,7 @@ namespace ts { | SyntaxKind.OverrideKeyword
| SyntaxKind.RequireKeyword
| SyntaxKind.ReturnKeyword
+ | SyntaxKind.SatisfiesKeyword
| SyntaxKind.SetKeyword
| SyntaxKind.StaticKeyword
| SyntaxKind.StringKeyword
@@ -1007,6 +1010,7 @@ namespace ts { | ExpressionWithTypeArguments
| AsExpression
| NonNullExpression
+ | SatisfiesExpression
| MetaProperty
| TemplateSpan
| Block
@@ -2815,6 +2819,12 @@ namespace ts { readonly expression: UnaryExpression;
}
+ export interface SatisfiesExpression extends Expression {
+ readonly kind: SyntaxKind.SatisfiesExpression;
+ readonly expression: Expression;
+ readonly type: TypeNode;
+ }
+
export type AssertionExpression =
| TypeAssertion
| AsExpression
@@ -7520,6 +7530,7 @@ namespace ts { export type OuterExpression =
| ParenthesizedExpression
| TypeAssertion
+ | SatisfiesExpression
| AsExpression
| NonNullExpression
| PartiallyEmittedExpression;
@@ -7856,6 +7867,8 @@ namespace ts { updateNonNullChain(node: NonNullChain, expression: Expression): NonNullChain;
createMetaProperty(keywordToken: MetaProperty["keywordToken"], name: Identifier): MetaProperty;
updateMetaProperty(node: MetaProperty, name: Identifier): MetaProperty;
+ createSatisfiesExpression(expression: Expression, type: TypeNode): SatisfiesExpression;
+ updateSatisfiesExpression(node: SatisfiesExpression, expression: Expression, type: TypeNode): SatisfiesExpression;
//
// Misc
diff --git a/src/compiler/utilities.ts b/src/compiler/utilities.tsindex 62a941df1f..c2ff0ab4fc 100644--- a/src/compiler/utilities.ts+++ b/src/compiler/utilities.ts@@ -1995,6 +1995,7 @@ namespace ts { case SyntaxKind.TaggedTemplateExpression:
case SyntaxKind.AsExpression:
case SyntaxKind.TypeAssertionExpression:
+ case SyntaxKind.SatisfiesExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.ParenthesizedExpression:
case SyntaxKind.FunctionExpression:
@@ -2095,6 +2096,8 @@ namespace ts { return (parent as ExpressionWithTypeArguments).expression === node && !isPartOfTypeNode(parent);
case SyntaxKind.ShorthandPropertyAssignment:
return (parent as ShorthandPropertyAssignment).objectAssignmentInitializer === node;
+ case SyntaxKind.SatisfiesExpression:
+ return node === (parent as SatisfiesExpression).expression;
default:
return isExpressionNode(parent);
}
@@ -3801,6 +3804,7 @@ namespace ts { return OperatorPrecedence.Member;
case SyntaxKind.AsExpression:
+ case SyntaxKind.SatisfiesExpression:
return OperatorPrecedence.Relational;
case SyntaxKind.ThisKeyword:
@@ -3859,6 +3863,7 @@ namespace ts { case SyntaxKind.InstanceOfKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.AsKeyword:
+ case SyntaxKind.SatisfiesKeyword:
return OperatorPrecedence.Relational;
case SyntaxKind.LessThanLessThanToken:
case SyntaxKind.GreaterThanGreaterThanToken:
@@ -5930,7 +5935,8 @@ namespace ts { case SyntaxKind.PropertyAccessExpression:
case SyntaxKind.NonNullExpression:
case SyntaxKind.PartiallyEmittedExpression:
- node = (node as CallExpression | PropertyAccessExpression | ElementAccessExpression | AsExpression | NonNullExpression | PartiallyEmittedExpression).expression;
+ case SyntaxKind.SatisfiesExpression:
+ node = (node as CallExpression | PropertyAccessExpression | ElementAccessExpression | AsExpression | NonNullExpression | PartiallyEmittedExpression | SatisfiesExpression).expression;
continue;
}
diff --git a/src/compiler/utilitiesPublic.ts b/src/compiler/utilitiesPublic.tsindex 229620a119..bc80f301e3 100644--- a/src/compiler/utilitiesPublic.ts+++ b/src/compiler/utilitiesPublic.ts@@ -1642,6 +1642,7 @@ namespace ts { case SyntaxKind.OmittedExpression:
case SyntaxKind.CommaListExpression:
case SyntaxKind.PartiallyEmittedExpression:
+ case SyntaxKind.SatisfiesExpression:
return true;
default:
return isUnaryExpressionKind(kind);
diff --git a/src/compiler/visitorPublic.ts b/src/compiler/visitorPublic.tsindex 29a112b062..02eeee55ad 100644--- a/src/compiler/visitorPublic.ts+++ b/src/compiler/visitorPublic.ts@@ -888,13 +888,19 @@ namespace ts { nodeVisitor(node.type, visitor, isTypeNode));
},
+ [SyntaxKind.SatisfiesExpression]: function visitEachChildOfSatisfiesExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
+ return context.factory.updateSatisfiesExpression(node,
+ nodeVisitor(node.expression, visitor, isExpression),
+ nodeVisitor(node.type, visitor, isTypeNode));
+ },
+
[SyntaxKind.NonNullExpression]: function visitEachChildOfNonNullExpression(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
return isOptionalChain(node) ?
context.factory.updateNonNullChain(node,
nodeVisitor(node.expression, visitor, isExpression)) :
context.factory.updateNonNullExpression(node,
nodeVisitor(node.expression, visitor, isExpression));
- },
+ },
[SyntaxKind.MetaProperty]: function visitEachChildOfMetaProperty(node, visitor, context, _nodesVisitor, nodeVisitor, _tokenVisitor) {
return context.factory.updateMetaProperty(node,
diff --git a/src/services/callHierarchy.ts b/src/services/callHierarchy.tsindex 1cbe4e58ad..5219698a44 100644--- a/src/services/callHierarchy.ts+++ b/src/services/callHierarchy.ts@@ -449,6 +449,10 @@ namespace ts.CallHierarchy { recordCallSite(node as AccessExpression);
forEachChild(node, collect);
break;
+ case SyntaxKind.SatisfiesExpression:
+ // do not descend into the type side of an assertion
+ collect((node as SatisfiesExpression).expression);
+ return;
}
if (isPartOfTypeNode(node)) {
diff --git a/src/services/classifier.ts b/src/services/classifier.tsindex 1b6705efed..ac15be962a 100644--- a/src/services/classifier.ts+++ b/src/services/classifier.ts@@ -369,6 +369,7 @@ namespace ts { case SyntaxKind.InstanceOfKeyword:
case SyntaxKind.InKeyword:
case SyntaxKind.AsKeyword:
+ case SyntaxKind.SatisfiesKeyword:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
diff --git a/src/services/completions.ts b/src/services/completions.tsindex bcc6efca67..36724b760a 100644--- a/src/services/completions.ts+++ b/src/services/completions.ts@@ -2675,6 +2675,9 @@ namespace ts.Completions {
case SyntaxKind.ExtendsKeyword:
return parentKind === SyntaxKind.TypeParameter;
+
+ case SyntaxKind.SatisfiesKeyword:
+ return parentKind === SyntaxKind.SatisfiesExpression;
}
}
return false;
@@ -3962,6 +3965,7 @@ namespace ts.Completions { return kind === SyntaxKind.AsyncKeyword
|| kind === SyntaxKind.AwaitKeyword
|| kind === SyntaxKind.AsKeyword
+ || kind === SyntaxKind.SatisfiesKeyword
|| kind === SyntaxKind.TypeKeyword
|| !isContextualKeyword(kind) && !isClassMemberCompletionKeyword(kind);
}
diff --git a/src/services/formatting/rules.ts b/src/services/formatting/rules.tsindex 76cd5aa6e4..144f97831b 100644--- a/src/services/formatting/rules.ts+++ b/src/services/formatting/rules.ts@@ -449,5 +449,6 @@ namespace ts.formatting { case SyntaxKind.TypePredicate:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
+ case SyntaxKind.SatisfiesExpression:
return true;
1234567#!/usr/bin/env bashset -euo pipefail
cd /workspace/typescriptpatch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch}git apply "$patch"lolbench-submit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960schema_version = "1.3"
[task]name = "lolbench/TypeScript_1"description = "Implement TypeScript satisfies operator."authors = [{ name = "LoLBench maintainers" }]keywords = ["lolbench", "coding-agent", "typescript"]
[metadata]instance_id = "TypeScript_1"source_instance_id = "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827"source_slug = "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827"docker_slug = "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827"dockerhub_image = "smartdub26/lolbench-linux:TypeScript_1-1.0.0"project = "TypeScript"repo = "microsoft/TypeScript"requirement_doc = "https://github.com/microsoft/TypeScript/issues/47920"pr_link = "https://github.com/microsoft/TypeScript/pull/46827"base_commit = "07157914eb26a6e9abdcda7255c4094c9efff4cd"merge_commit = "a73f1c7ce4b97bf13e6c3f2341412b0216d92933"test_level = "system"source_history_policy = "ancestors-only"lolbench_test_modes = ["orig", "aug", "union"]default_lolbench_suite = "union"canonical_lolbench_suite = "union"augmentation_available = trueverifier_network_policy = "public"verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase."
[environment]build_timeout_sec = 3600.0docker_image = "smartdub26/lolbench-linux:TypeScript_1-1.0.0"network_mode = "public"os = "linux"cpus = 4memory_mb = 7168storage_mb = 20480
[agent]timeout_sec = 21600.0user = "agent"network_mode = "allowlist"allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"]
[verifier]timeout_sec = 7200.0user = "root"environment_mode = "separate"network_mode = "public"
[verifier.env]LOLBENCH_SUITE = "union"
[verifier.environment]docker_image = "smartdub26/lolbench-linux:TypeScript_1-1.0.0"network_mode = "public"os = "linux"cpus = 4memory_mb = 7168storage_mb = 2048012345678910111213141516services: main: pull_policy: missing volumes: - type: bind source: . target: /tests read_only: true - type: bind source: ./private target: /opt/lolbench/private read_only: true - type: bind source: ../solution target: /solution read_only: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185diff --git a/tests/cases/fourslash/satisfiesAugCompilerApi.ts b/tests/cases/fourslash/satisfiesAugCompilerApi.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/satisfiesAugCompilerApi.ts@@ -0,0 +1,76 @@+/// <reference path="fourslash.ts" />++////const placeholder = 0;++const source = "const result = value satisfies Target;";+const sourceFile = ts.createSourceFile("satisfiesAug.ts", source, ts.ScriptTarget.Latest, /*setParentNodes*/ true, ts.ScriptKind.TS);+const declaration = (sourceFile.statements[0] as ts.VariableStatement).declarationList.declarations[0];+const initializer = declaration.initializer as ts.SatisfiesExpression;++assert.strictEqual(initializer.kind, ts.SyntaxKind.SatisfiesExpression);++const printed = ts.createPrinter().printNode(ts.EmitHint.Expression, initializer, sourceFile);+assert.strictEqual(printed, "value satisfies Target");++const transpiled = ts.transpileModule(source, {+ compilerOptions: { target: ts.ScriptTarget.ES2020 },+}).outputText.trim();+assert.strictEqual(transpiled, "const result = value;");++const transformed = ts.transform(sourceFile, [+ context => root => ts.visitNode(root, function visit(node): ts.Node {+ if (+ ts.isTypeReferenceNode(node) &&+ ts.isIdentifier(node.typeName) &&+ node.typeName.text === "Target"+ ) {+ return context.factory.updateTypeReferenceNode(+ node,+ context.factory.createIdentifier("Replacement"),+ node.typeArguments,+ );+ }+ return ts.visitEachChild(node, visit, context);+ }),+]);+try {+ const transformedSourceFile = transformed.transformed[0] as ts.SourceFile;+ const transformedDeclaration =+ (transformedSourceFile.statements[0] as ts.VariableStatement).declarationList.declarations[0];+ const transformedInitializer = transformedDeclaration.initializer as ts.SatisfiesExpression;+ const transformedText = ts.createPrinter().printNode(+ ts.EmitHint.Expression,+ transformedInitializer,+ transformedSourceFile,+ );+ assert.strictEqual(transformedText, "value satisfies Replacement");+}+finally {+ transformed.dispose();+}++const factoryExpression = ts.factory.createSatisfiesExpression(+ ts.factory.createIdentifier("factoryValue"),+ ts.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),+);+assert.strictEqual(+ ts.createPrinter().printNode(ts.EmitHint.Expression, factoryExpression, sourceFile),+ "factoryValue satisfies number",+);++const factoryTransformer = context => source => {+ const factoryExport = context.factory.createExportAssignment(+ undefined,+ false,+ context.factory.createSatisfiesExpression(+ context.factory.createIdentifier("factoryValue"),+ context.factory.createKeywordTypeNode(ts.SyntaxKind.NumberKeyword),+ ),+ );+ return context.factory.updateSourceFile(source, [factoryExport]);+};+const factoryTranspile = ts.transpileModule("export const seed = 0;", {+ compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext },+ transformers: { before: [factoryTransformer] },+}).outputText.trim();+assert.strictEqual(factoryTranspile, "export default factoryValue;");diff --git a/tests/cases/fourslash/satisfiesAugCompletionKeyword.ts b/tests/cases/fourslash/satisfiesAugCompletionKeyword.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/satisfiesAugCompletionKeyword.ts@@ -0,0 +1,14 @@+/// <reference path="fourslash.ts" />++////const first = { a: 1 } /*top*/+////function outer() {+//// const second = { a: 1 } /*nested*/+////}+////type Target = { a: number };+////const checked = { a: 1 } satisfies /**/++verify.completions({+ marker: ["top", "nested"],+ includes: [{ name: "satisfies", sortText: completion.SortText.GlobalsOrKeywords }]+});+verify.completions({ marker: "", includes: "Target" });diff --git a/tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts b/tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts@@ -0,0 +1,8 @@+/// <reference path="fourslash.ts" />++//// function /**/target() { return { ok: true }; }+//// const checked = target() satisfies ReturnType<typeof target>;++assert.strictEqual(typeof ts.SyntaxKind.SatisfiesExpression, "number");+goTo.marker();+verify.baselineCallHierarchy();diff --git a/tests/cases/fourslash/asOperatorAugCompletionP2P.ts b/tests/cases/fourslash/asOperatorAugCompletionP2P.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/asOperatorAugCompletionP2P.ts@@ -0,0 +1,6 @@+/// <reference path="fourslash.ts" />++////type ExistingTarget = { a: number };+////const value = { a: 1 } as /**/++verify.completions({ marker: "", includes: "ExistingTarget", excludes: "satisfies" });diff --git a/tests/cases/fourslash/contextualTypingAugP2P.ts b/tests/cases/fourslash/contextualTypingAugP2P.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/contextualTypingAugP2P.ts@@ -0,0 +1,8 @@+/// <reference path="fourslash.ts" />++////interface CallbackBox { run(value: number): string; }+////const box: CallbackBox = { run: /*param*/value => value.toFixed() };+////box.run(1);++verify.quickInfoAt("param", "(parameter) value: number");+verify.noErrors();diff --git a/tests/baselines/reference/satisfiesAugCallHierarchyTypeSide.callHierarchy.txt b/tests/baselines/reference/satisfiesAugCallHierarchyTypeSide.callHierarchy.txtnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/baselines/reference/satisfiesAugCallHierarchyTypeSide.callHierarchy.txt@@ -0,0 +1,37 @@+╭ name: target+├ kind: function+├ file: /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts+├ span:+│ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:1-1:43+│ │ 1: function target() { return { ok: true }; }+│ │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+│ ╰+├ selectionSpan:+│ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:10-1:16+│ │ 1: function target() { return { ok: true }; }+│ │ ^^^^^^+│ ╰+├ incoming:+│ ╭ from:+│ │ ╭ name: /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts+│ │ ├ kind: script+│ │ ├ file: /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts+│ │ ├ span:+│ │ │ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:1-2:62+│ │ │ │ 1: function target() { return { ok: true }; }+│ │ │ │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+│ │ │ │ 2: const checked = target() satisfies ReturnType<typeof target>;+│ │ │ │ ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^+│ │ │ ╰+│ │ ├ selectionSpan:+│ │ │ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:1:1-1:1+│ │ │ │ 1: function target() { return { ok: true }; }+│ │ │ │ <+│ │ │ ╰+│ │ ╰ incoming: none+│ ├ fromSpans:+│ │ ╭ /tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts:2:17-2:23+│ │ │ 2: const checked = target() satisfies ReturnType<typeof target>;+│ │ │ ^^^^^^+│ ╰ ╰+╰ outgoing: none12345678910111213tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_js.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.tstests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts123tests/cases/fourslash/satisfiesAugCompletionKeyword.tstests/cases/fourslash/satisfiesAugCompilerApi.tstests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950tests/cases/conformance/expressions/asOperator/asOpEmitParens.tstests/cases/conformance/expressions/asOperator/asOperator1.tstests/cases/conformance/expressions/asOperator/asOperator2.tstests/cases/conformance/expressions/asOperator/asOperator3.tstests/cases/conformance/expressions/asOperator/asOperator4.tstests/cases/conformance/expressions/asOperator/asOperatorASI.tstests/cases/conformance/expressions/asOperator/asOperatorAmbiguity.tstests/cases/conformance/expressions/asOperator/asOperatorContextualType.tstests/cases/conformance/expressions/asOperator/asOperatorNames.tstests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.tstests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.tstests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping1.tstests/cases/conformance/expressions/contextualTyping/getSetAccessorContextualTyping.tstests/cases/conformance/expressions/contextualTyping/iterableContextualTyping1.tstests/cases/conformance/expressions/contextualTyping/objectLiteralContextualTyping.tstests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping1.tstests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping1.tstests/cases/conformance/expressions/arrayLiterals/arrayLiteralInference.tstests/cases/conformance/expressions/arrayLiterals/arrayLiterals.tstests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES5.tstests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES6.tstests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsReference.tstests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.tstests/cases/conformance/expressions/assignmentOperator/assignmentTypeNarrowing.tstests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.tstests/cases/conformance/expressions/assignmentOperator/assignmentGenericLookupTypeNarrowing.tstests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCanBeAssigned.tstests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCannotBeAssigned.tstests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentWithInvalidOperands.tstests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentLHSCanBeAssigned.tstests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.tstests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsReference.tstests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.tstests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping2.tstests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping3.tstests/cases/conformance/expressions/contextualTyping/generatedContextualTyping.tstests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping2.tstests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping3.tstests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping2.tstests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping3.tstests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.tstests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.tstests/cases/conformance/expressions/typeAssertions/constAssertionOnEnum.tstests/cases/conformance/expressions/typeAssertions/constAssertions.tstests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions01.tstests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions02.tstests/cases/conformance/expressions/typeAssertions/typeAssertions.tstests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsBooleanType.tstests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsNumberType.tstests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsObjectType.ts12tests/cases/fourslash/asOperatorAugCompletionP2P.tstests/cases/fourslash/contextualTypingAugP2P.ts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339#!/usr/bin/env bash# LoLBench runner for microsoft/TypeScript PR-46827 (satisfies operator).## Eval contract:# docker run --rm --network=none \# -v $(pwd)/solution.patch:/in/solution.patch:ro \# -v $(pwd)/out:/out \# lolbench/apache-ts-pr-46827:1# → /out/agent_report.json (sanitized).## Validation modes:# LOLBENCH_MODE=validate_pre # F2P FAIL (parser doesn't know `satisfies`), P2P PASS# LOLBENCH_MODE=validate_post # all PASS
set -uo pipefailPRIV=/opt/lolbench/privateWS=/workspaceTS=$WS/typescriptMODE=${LOLBENCH_MODE:-eval}SUITE=${LOLBENCH_SUITE:-orig}
case "$SUITE" in orig|aug|union) ;; *) echo "[run_tests $MODE] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;;esac
HAS_AUG=0if [ -f "$PRIV/eval_tests_aug.patch" ] \ && [ -f "$PRIV/f2p_aug.txt" ] \ && [ -f "$PRIV/p2p_aug.txt" ]; then HAS_AUG=1fiif [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then echo "[run_tests $MODE/$SUITE] WARN: no augmented sidecar shipped; falling back to orig" >&2 SUITE=origfi
log() { echo "[run_tests $MODE/$SUITE] $*" >&2; }die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; }
FAIL_TO_PASS=()PASS_TO_PASS=()
emit_error() { local cat=$1 applied=$2 build_status=$3 local f2p_n=${#FAIL_TO_PASS[@]} local p2p_n=${#PASS_TO_PASS[@]} python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" "$SUITE" "$HAS_AUG" <<'EOF' >/out/agent_report.jsonimport json, syscat, applied_s, build_s, f2p_n, p2p_n, suite, has_aug_s = sys.argv[1:8]applied = applied_s.lower() == "true"print(json.dumps({ "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", "suite": suite, "augmentation_available": has_aug_s == "1", "applied": applied, "build": {"status": build_s}, "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, "resolved": False, "error_categories": [cat]}, indent=2))EOF}
mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt")mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt")FAIL_TO_PASS_AUG=()PASS_TO_PASS_AUG=()if [ "$HAS_AUG" -eq 1 ]; then mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt")fi
case "$SUITE" in orig) FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") ;; aug) FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") ;; union) FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") ;;esac
F2P_EFFECTIVE=$WS/.f2p_effective.txtP2P_EFFECTIVE=$WS/.p2p_effective.txtprintf '%s\n' "${FAIL_TO_PASS[@]}" >"$F2P_EFFECTIVE"printf '%s\n' "${PASS_TO_PASS[@]}" >"$P2P_EFFECTIVE"
# Sanity-check spec ↔ selectors agreepython3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$SUITE" <<'EOF' || die "spec/selector mismatch"import json, sysspec = json.load(open(sys.argv[1]))orig_f2p = [l.strip() for l in open(sys.argv[2]) if l.strip()]orig_p2p = [l.strip() for l in open(sys.argv[3]) if l.strip()]eff_f2p = [l.strip() for l in open(sys.argv[4]) if l.strip()]eff_p2p = [l.strip() for l in open(sys.argv[5]) if l.strip()]suite = sys.argv[6]aug = spec.get("augmented", {})expected = { "orig": (spec["fail_to_pass"], spec["pass_to_pass"]), "aug": (aug.get("fail_to_pass", []), aug.get("pass_to_pass", [])), "union": (orig_f2p + aug.get("fail_to_pass", []), orig_p2p + aug.get("pass_to_pass", [])),}[suite]sys.exit(0 if expected == (eff_f2p, eff_p2p) else 1)EOF
# ---- pick source-side patch by mode ---------------------------------SRC_PATCH=""case "$MODE" in validate_pre) SRC_PATCH="" ;; validate_post) if [ -f /solution/solution.patch ]; then SRC_PATCH=/solution/solution.patch else SRC_PATCH="$PRIV/solution.patch" fi ;; eval) if [ ! -f /in/solution.patch ]; then log "no /in/solution.patch mounted" emit_error missing_solution_patch false skipped exit 0 fi AGENT_PATCH=/tmp/lolbench_agent_patch.diff cp /in/solution.patch "$AGENT_PATCH" chmod 0600 "$AGENT_PATCH" SRC_PATCH="$AGENT_PATCH" ;; *) die "unknown LOLBENCH_MODE=$MODE" ;;esac
# ---- reset workspace + apply patches --------------------------------cd "$TS"git config --global --add safe.directory "$TS"git reset --hard >/dev/null 2>&1git clean -fdx -e node_modules -e built >/dev/null 2>&1
if [ -n "$SRC_PATCH" ]; then if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then log "source patch did not apply cleanly:"; cat /tmp/apply.err >&2 emit_error patch_apply_failure false skipped; exit 0 fi git apply "$SRC_PATCH" # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the # eval test patches own (test fixtures the agent must not modify), restore # those paths (both sides of every diff/rename) to the base state so # eval_tests(.aug).patch always applies. Agent source changes are preserved. for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do [ -f "$_lb_ep" ] || continue { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do [ -n "$_lb_f" ] || continue git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true done donefi
# eval_tests.patch is ALWAYS applied — the test files + baselines it# adds are needed in BOTH pre- and post-state. In pre-state without# solution.patch, running the new tests produces baseline mismatches# (parser doesn't tokenize `satisfies` → bogus errors in .errors.txt)# which is exactly the FAIL behavior §7 requires.if ! git apply --ignore-space-change --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then log "eval_tests.patch did not apply cleanly:"; cat /tmp/apply.err >&2 emit_error eval_patch_apply_failure true skipped; exit 0figit apply --ignore-space-change "$PRIV/eval_tests.patch"if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then log "eval_tests_aug.patch did not apply cleanly:"; cat /tmp/apply.err >&2 emit_error eval_aug_patch_apply_failure true skipped; exit 0 fi git apply "$PRIV/eval_tests_aug.patch"fi
# ---- rebuild local tsc + test infra after patches ----------------------BUILD_LOG=$WS/.build.logTEST_LOG=$WS/.test.log: >"$BUILD_LOG" >"$TEST_LOG"
log "running 'npx gulp local' to rebuild tsc with patches applied"npx gulp local >"$BUILD_LOG" 2>&1build_rc=$?if [ "$build_rc" -ne 0 ]; then log "build failed (rc=$build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 emit_error build_failure true failed; exit 0fi
log "running 'npx gulp tests' to rebuild the test runner harness"npx gulp tests >>"$BUILD_LOG" 2>&1tests_build_rc=$?if [ "$tests_build_rc" -ne 0 ]; then log "test-harness build failed (rc=$tests_build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 emit_error build_failure true failed; exit 0fi
# ---- build the regex selector that runtests --tests=... accepts -----# TypeScript's runtests uses a regex matched against mocha test names.# For conformance tests the name typically contains the source path# fragment, e.g. for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts# the test name includes "typeSatisfaction" / "typeSatisfaction.ts".## Strategy: union of UNIQUE BASENAMES (without .ts) — every selector's# basename is unique among the 13+24 we ship. The resulting regex is# matched anywhere within the test name (not anchored), so subdir# selectors stay correct.RUNTESTS_REGEX=$(python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" <<'PY'import os, sysids = []for p in sys.argv[1:]: for l in open(p): l = l.strip() if l: base = os.path.splitext(os.path.basename(l))[0] ids.append(base)# Sort longest-first so e.g. `typeSatisfaction_contextualTyping1` matches# before the shorter `typeSatisfaction`.ids = sorted(set(ids), key=len, reverse=True)print("|".join(map(__import__("re").escape, ids)))PY)log "runtests selector regex: ${RUNTESTS_REGEX:0:80}..."
# ---- run the union of F2P + P2P tests ----------------------------------# Invoke mocha directly (bypassing the gulp wrapper) so the post-tests# eslint phase doesn't fail the whole gulp run. The exact arguments# mirror what `gulp runtests --tests=<regex> --reporter=tap` invokes# internally (verified by running the gulp version and inspecting the# spawned mocha command line).log "running mocha directly with selector regex"/usr/bin/node "$TS/node_modules/mocha/bin/_mocha" \ -R "$TS/scripts/failed-tests.js" \ -O "reporter=tap" \ -g "$RUNTESTS_REGEX" \ --no-colors -t 40000 \ "$TS/built/local/run.js" \ >>"$TEST_LOG" 2>&1 || true
# ---- parse the TAP output + emit reports -------------------------------python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" "$HAS_AUG" "$TEST_LOG" <<'PYEOF'"""Parse mocha's TAP-style output and bucket per-selector PASS/FAIL.
mocha's TAP reporter emits lines like: ok 151 conformance tests conformance tests for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts Correct errors for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts not ok 152 ... <reason>
Note: NO `-` separator between the number and description, despitethe TAP spec. We extract the .ts path from anywhere in the line.
Each .ts file produces ~6 sub-tests (Correct errors / moduleresolution tracing / sourcemap content / JS output / Sourcemapoutput / type/symbol baselines). A .ts file PASSES iff everysub-test PASSES."""import json, os, re, sysf2p_file, p2p_file, mode, suite, has_aug_s, log_path = sys.argv[1:7]has_aug = has_aug_s == "1"
f2p_ids = [l.strip() for l in open(f2p_file) if l.strip()]p2p_ids = [l.strip() for l in open(p2p_file) if l.strip()]
# Map path → set of statuses observed for that path's sub-tests.file_statuses = {sid: set() for sid in f2p_ids + p2p_ids}spec_paths = {sid for sid in f2p_ids + p2p_ids}
try: log = open(log_path).read()except FileNotFoundError: log = ""
# mocha TAP output: "ok N <description>" or "not ok N <description>".TAP_LINE = re.compile(r'^(ok|not ok)\s+\d+\s+(.*)$')# Extract a tests/cases/... .ts path from the description.TS_PATH = re.compile(r'(tests/cases/[^\s]+?\.ts)')
for line in log.splitlines(): m = TAP_LINE.match(line) if not m: continue verdict, desc = m.group(1), m.group(2) # Find ALL .ts paths in the description — usually 2 (e.g. "conformance # tests for X Correct errors for X"). All point to the same file. paths = set(TS_PATH.findall(desc)) for p in paths: if p not in spec_paths: continue if " # SKIP" in desc.upper() or " # TODO" in desc.upper(): file_statuses[p].add("SKIPPED") elif verdict == "ok": file_statuses[p].add("PASSED") else: file_statuses[p].add("FAILED")
results = {}for p, statuses in file_statuses.items(): if not statuses: results[p] = "ERROR" # no sub-tests matched → test never ran elif "FAILED" in statuses: results[p] = "FAILED" elif "SKIPPED" in statuses and "PASSED" not in statuses: results[p] = "SKIPPED" else: results[p] = "PASSED"
def bucket(ids): out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} for sid in ids: out[results.get(sid, "ERROR")].append(sid) return out
f2p = bucket(f2p_ids)p2p = bucket(p2p_ids)resolved = (len(f2p["PASSED"]) == len(f2p_ids) and len(p2p["PASSED"]) == len(p2p_ids))
grader = { "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", "mode": mode, "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, "f2p": f2p, "p2p": p2p, "resolved": resolved}def cnts(d, ids): return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]), "errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)}agent = { "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, "f2p": cnts(f2p, f2p_ids), "p2p": cnts(p2p, p2p_ids), "resolved": resolved, "error_categories": []}json.dump(grader, open("/out/grader_report.json","w"), indent=2)json.dump(agent, open("/out/agent_report.json","w"), indent=2)print(json.dumps(grader, indent=2))PYEOF123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507{ "instance_id": "TypeScript_Issue-47920_satisfies-operator-to-ensure-an-expression-matches-some-type-safe-upcast_PR-46827", "project": "microsoft/TypeScript", "requirement_doc": "https://github.com/microsoft/TypeScript/issues/47920", "requirement_doc_note": "Design issue #47920 ('satisfies operator to ensure an expression matches some type-safe upcast'). The original feature request that motivated the PR is issue #7481, referenced in the PR title and body.", "pr_link": "https://github.com/microsoft/TypeScript/pull/46827", "pr_merge_date": "2022-08-26", "language": "TypeScript", "build_system": "npm + gulp (PR-46827 era; later TypeScript migrated to hereby)", "scope": { "pr_touched_modules": [ "src/compiler", "src/services", "src/harness", "src/testRunner", "tests/cases", "tests/baselines" ], "in_scope_modules": [ "src/compiler", "src/services", "src/harness", "src/testRunner" ], "build_modules": [ "src" ], "p2p_modules": [ "tests/cases/conformance/expressions" ], "pr_total_files_changed": 102, "in_scope_production_files": 20, "in_scope_test_files": 82, "out_of_scope_files_dropped": 0, "out_of_scope_summary": "No files dropped. All 102 PR files are either compiler/service source (20) or test fixtures + their baselines (82). TypeScript's baseline files are required for the test framework \u2014 they ARE the expected outputs that compiletest compares against." }, "base_commit": "07157914eb26a6e9abdcda7255c4094c9efff4cd", "base_commit_note": "Parent of the squash-merge commit on main. The merge commit 164dddc4 has a single parent (07157914) \u2014 the PR was merged via GitHub's squash-merge button. Use the parent..merge diff for the patch content. GitHub's pr.base.sha = c4eb37c8 is an older snapshot from when the PR was opened (May 2022) and predates the squash by ~3 months; do NOT use it as the base \u2014 the merge tree was applied against where main had advanced to (07157914 in Aug 2022).", "merge_commit_sha": "164dddc48e1eaa83780b8e72bc7afeebe768437b", "pr_head_sha": "a73f1c7ce4b97bf13e6c3f2341412b0216d92933", "pr_base_sha_github": "c4eb37c8a0d5915d64e3992a91a34724aab19fe6", "merge_style": "squash-merge \u2014 merge_commit_sha (164dddc4) has one parent (07157914); the PR's 19 individual commits were squashed into this single commit on main.", "diff_source": "Patches reconstructed via `git diff 07157914..164dddc4` (parent..squash-merge on main). GitHub PR base/head SHAs preserved for provenance audit only.", "solution_patch_sha256": "f7eb19d647450fd5d6ee8b5bac0d15332125069b61159198cab81ffda58b2740", "eval_tests_patch_sha256": "e23b87a8fefad5a605309fea4550d5c044a3fb2bdc1c4f921909aa6f15803eb1", "toolchain": { "node": "16.x (TypeScript 4.9-era; nvm or apt-installed)", "npm": "8.x", "test_framework": "TypeScript's mocha-based runtests (`gulp runtests --tests=<regex>`); each .ts file in tests/cases/ is a baseline-comparison test against tests/baselines/reference/", "host_target": "linux/amd64", "base_image": "lolbench/typescript-base:1 (NEW \u2014 needs creation; Ubuntu 22.04 + Node 16 + npm + git + python3)" }, "fail_to_pass": [ "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfactionWithDefaultExport.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping1.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_contextualTyping2.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_ensureInterfaceImpl.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_js.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_optionalMemberConformance.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propNameConstraining.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyNameFulfillment.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance1.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance2.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_propertyValueConformance3.ts", "tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction_vacuousIntersectionOfContextualTypes.ts" ], "pass_to_pass": [ "tests/cases/conformance/expressions/asOperator/asOpEmitParens.ts", "tests/cases/conformance/expressions/asOperator/asOperator1.ts", "tests/cases/conformance/expressions/asOperator/asOperator2.ts", "tests/cases/conformance/expressions/asOperator/asOperator3.ts", "tests/cases/conformance/expressions/asOperator/asOperator4.ts", "tests/cases/conformance/expressions/asOperator/asOperatorASI.ts", "tests/cases/conformance/expressions/asOperator/asOperatorAmbiguity.ts", "tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts", "tests/cases/conformance/expressions/asOperator/asOperatorNames.ts", "tests/cases/conformance/expressions/contextualTyping/argumentExpressionContextualTyping.ts", "tests/cases/conformance/expressions/contextualTyping/arrayLiteralExpressionContextualTyping.ts", "tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping1.ts", "tests/cases/conformance/expressions/contextualTyping/getSetAccessorContextualTyping.ts", "tests/cases/conformance/expressions/contextualTyping/iterableContextualTyping1.ts", "tests/cases/conformance/expressions/contextualTyping/objectLiteralContextualTyping.ts", "tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping1.ts", "tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping1.ts", "tests/cases/conformance/expressions/arrayLiterals/arrayLiteralInference.ts", "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals.ts", "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES5.ts", "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals2ES6.ts", "tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsReference.ts", "tests/cases/conformance/expressions/assignmentOperator/assignmentLHSIsValue.ts", "tests/cases/conformance/expressions/assignmentOperator/assignmentTypeNarrowing.ts", "tests/cases/conformance/expressions/arrayLiterals/arrayLiterals3.ts", "tests/cases/conformance/expressions/assignmentOperator/assignmentGenericLookupTypeNarrowing.ts", "tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCanBeAssigned.ts", "tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentLHSCannotBeAssigned.ts", "tests/cases/conformance/expressions/assignmentOperator/compoundAdditionAssignmentWithInvalidOperands.ts", "tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentLHSCanBeAssigned.ts", "tests/cases/conformance/expressions/assignmentOperator/compoundArithmeticAssignmentWithInvalidOperands.ts", "tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsReference.ts", "tests/cases/conformance/expressions/assignmentOperator/compoundAssignmentLHSIsValue.ts", "tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping2.ts", "tests/cases/conformance/expressions/contextualTyping/functionExpressionContextualTyping3.ts", "tests/cases/conformance/expressions/contextualTyping/generatedContextualTyping.ts", "tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping2.ts", "tests/cases/conformance/expressions/contextualTyping/parenthesizedContexualTyping3.ts", "tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping2.ts", "tests/cases/conformance/expressions/contextualTyping/superCallParameterContextualTyping3.ts", "tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping1.ts", "tests/cases/conformance/expressions/contextualTyping/taggedTemplateContextualTyping2.ts", "tests/cases/conformance/expressions/typeAssertions/constAssertionOnEnum.ts", "tests/cases/conformance/expressions/typeAssertions/constAssertions.ts", "tests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions01.ts", "tests/cases/conformance/expressions/typeAssertions/duplicatePropertiesInTypeAssertions02.ts", "tests/cases/conformance/expressions/typeAssertions/typeAssertions.ts", "tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsBooleanType.ts", "tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsNumberType.ts", "tests/cases/conformance/expressions/conditonalOperator/conditionalOperatorConditionIsObjectType.ts" ], "triage": { "test_level_policy": "Every F2P and P2P entry is a single .ts file under tests/cases/. Each is system-level by construction \u2014 TypeScript's runtests harness compiles the file end-to-end with the freshly-built tsc, runs through parser+checker+emitter+type-printer, and compares the emitted .js, .types, .symbols, and .errors.txt against the corresponding files under tests/baselines/reference/. A test fails if ANY baseline differs. No unit-level tests selected.", "f2p_test_classes": { "system_e2e": { "typeSatisfaction conformance (13)": "tests/cases/conformance/expressions/typeSatisfaction/*.ts \u2014 13 NEW test files added by eval_tests.patch. Each exercises a different facet of the satisfies operator: basic syntax (typeSatisfaction.ts), contextual typing (\u00d72), interface conformance, JS-mode parsing, optional members, property-name fulfillment, value conformance (\u00d73), property-name constraining, vacuous intersection, default-export forms. Each .ts file drives a full parser+checker+emitter+type-printer pass through tsc; the runtests harness compares the emitted .js / .types / .symbols / .errors.txt against the baseline siblings." }, "module_level": {}, "f2p_test_classes_excluded_as_unit": [ "tests/cases/fourslash/completionSatisfiesKeyword.ts \u2014 fourslash test using verify.completions(); narrower than full-compile baseline tests, probes only the language service completion API. Excluded per the system-level rule.", "tests/cases/fourslash/satisfiesOperatorCompletion.ts \u2014 same rationale as above." ] }, "test_compile_failure_pre_state": "Expected: at base, the parser doesn't recognize the satisfies keyword (it's a contextual keyword added by solution.patch). The compiler treats `as satisfies` literally \u2192 produces unexpected errors \u2192 baseline comparison fails. Every F2P test gets a baseline mismatch in pre-state, surfacing as FAIL. Some fourslash tests may instead error out trying to complete an unknown keyword.", "p2p_isolation": "All 50 P2P selectors are .ts files in tests/cases/conformance/expressions/ across {asOperator, contextualTyping, arrayLiterals, assignmentOperator, typeAssertions, conditonalOperator} subdirs \u2014 same expression-typing code-paths the satisfies PR touches (checker.ts type assertion path, emitter.ts emission, parser.ts contextual-keyword tokenization), but on UNCHANGED test files. No taint surface: TypeScript baseline tests are file-level isolated \u2014 each .ts file plus its .baseline siblings is a complete self-contained test scenario.", "runtests_selector_note": "TypeScript's runtests harness selects tests via a regex match against the BASENAME of the .ts file (not the full path). An F2P/P2P selector like `tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts` translates to a runtests filter regex `typeSatisfaction\\.ts` (or, for safety, the full path joined with `|`). run_tests.sh must construct this regex from the f2p.txt/p2p.txt lines." }, "f2p_entry_count": 13, "p2p_entry_count": 50, "validated_at": "2026-06-20", "p2p_base_existence_check": "All 50 P2P paths were verified present at base_commit 07157914eb26a6e9abdcda7255c4094c9efff4cd inside the built eval image during P2P expansion (2026-06-15). The 26 added selectors are pre-existing TypeScript conformance tests and do not appear in solution.patch or eval_tests.patch.", "eval_tests_patch_baseline_note": "eval_tests.patch BOTH adds new .ts test cases under tests/cases/conformance/expressions/typeSatisfaction/ AND modifies existing baseline files under tests/baselines/reference/ (the new satisfies keyword changes some pre-existing baselines that reference the keyword class). P2P selectors are NOT in any of the modified-baseline files, so no taint surface.", "augmented": { "suite_support": { "env": "LOLBENCH_SUITE", "modes": [ "orig", "aug", "union" ], "default": "orig" }, "eval_tests_patch": "eval_tests_aug.patch", "eval_tests_aug_patch_sha256": "28c25e341f62f86fde21b8b36a03548421d77612197d5c01420436f0ab140e78", "f2p_aug_sha256": "2db6678c5e6cf835287d93e1001a819031d8f647dd3c29a319aa2ee7001160be", "p2p_aug_sha256": "a0c75d3384671ed97a629404df0d71c235e6acf789e6433fc3fe4f09e1ae5426", "fail_to_pass": [ "tests/cases/fourslash/satisfiesAugCompletionKeyword.ts", "tests/cases/fourslash/satisfiesAugCompilerApi.ts", "tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts" ], "pass_to_pass": [ "tests/cases/fourslash/asOperatorAugCompletionP2P.ts", "tests/cases/fourslash/contextualTypingAugP2P.ts" ], "targets_mutants": [ "mutant_005_printer_emits_as_keyword_for_satisfies", "mutant_010_public_visitor_skips_satisfies_type", "mutant_012_satisfies_keyword_not_offered_in_completions" ], "equivalent_mutants": {}, "coverage_gate": { "minimum_line_coverage_percent": 80, "status": "passed", "coverage_report": "coverage_out/coverage_report_union.json", "baseline_coverage_report": "coverage_out/coverage_report_orig.json", "augmented_coverage_report": "coverage_out/coverage_report_aug.json", "measurement_note": "V8/c8 line coverage over executable TypeScript compiler and services lines added by solution.patch; union mode runs original plus augmented F2P/P2P selectors.", "baseline_union_line_coverage_percent": 100.0, "augmented_only_union_line_coverage_percent": 100.0, "union_line_coverage_percent": 100.0, "executable_lines_in_patch": 109, "union_covered_lines": 109, "coverage_complete": true }, "triage": { "test_level_policy": "Augmented F2P uses TypeScript fourslash tests to drive public compiler and language-service APIs through the project harness: parser output, ts.createPrinter, ts.transpileModule, ts.transform/visitEachChild, completions, and call hierarchy. Augmented P2P uses unrelated as-operator and contextual-typing fourslash checks that do not mention satisfies.", "fail_to_pass": { "tests/cases/fourslash/satisfiesAugCompletionKeyword.ts": { "requirement_sections": [ "TL;DR" ], "public_surface": "TypeScript language-service completions through the fourslash verify.completions harness.", "mutants_targeted": [ "mutant_012_satisfies_keyword_not_offered_in_completions" ], "rationale": "Checks that the contextual keyword is offered at expression positions and that the type side after `satisfies` still offers target types. This makes the public editor-facing keyword support observable." }, "tests/cases/fourslash/satisfiesAugCompilerApi.ts": { "requirement_sections": [ "Scenario Candidates > Safe Upcast" ], "public_surface": "TypeScript public compiler API through createSourceFile, createPrinter, transpileModule, factory.createSatisfiesExpression, and ts.transform.", "mutants_targeted": [ "mutant_005_printer_emits_as_keyword_for_satisfies" ], "rationale": "Checks that public printer and transformer APIs preserve `satisfies` syntax while emit/transpile still erases the type-only operator." }, "tests/cases/fourslash/satisfiesAugCallHierarchyTypeSide.ts": { "requirement_sections": [ "Scenario Candidates > Safe Upcast" ], "public_surface": "TypeScript language-service call hierarchy over a satisfies expression whose type side references a function.", "mutants_targeted": [ "mutant_010_public_visitor_skips_satisfies_type" ], "rationale": "Checks that public AST traversal reaches the satisfies type child so editor features can see references that appear on the type side." } }, "pass_to_pass": { "tests/cases/fourslash/asOperatorAugCompletionP2P.ts": { "requirement_sections": [ "Scenario Candidates > Safe Upcast" ], "public_surface": "Existing TypeScript as-operator completion behavior through fourslash completions.", "stability_goal": "The new satisfies keyword must not disturb existing `as` expression completions or inject satisfies into the type-completion position after `as`.", "rationale": "Pins adjacent unchanged type-assertion behavior in the same expression family while staying independent of the new satisfies syntax." }, "tests/cases/fourslash/contextualTypingAugP2P.ts": { "requirement_sections": [ "Scenario Candidates > Contextual Typing" ], "public_surface": "Existing contextual typing and quick-info behavior through fourslash quickInfo/noErrors.", "stability_goal": "Contextual typing of function parameters in object literals must remain stable for existing annotations.", "rationale": "The satisfies implementation reuses contextual typing machinery; this P2P selector guards an unchanged contextual typing path without mentioning satisfies." } } }, "mutant_set_revision": { "date": "2026-06-16", "removed": [ "mutant_008_factory_omits_typescript_transform_flag", "mutant_011_call_hierarchy_counts_type_side_references" ], "reason": "equivalent", "note": "2 equivalent mutant(s) removed from mutations/ per the 2026-06-16 mutant-kill audit (no \u00a76-clean test can kill an equivalent mutant); union now kills all 10 remaining mutants.", "new_total": 10, "union_kills_all_remaining": true } }, "repo": "microsoft/TypeScript", "image": "lolbench/typescript_1:1.0.0", "agent_contract": { "input": "/in/solution.patch", "output": "/out/agent_report.json", "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/typescript_1:1.0.0" }, "test_framework": "node_test", "test_level": "system", "test_cmd_template": "npm test -- <test_selector>", "log_parser": "node_test", "coverage": { "orig": 100.0, "aug": 100.0, "union": 100.0, "denominator": "union_executable_lines" }, "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_1-1.0.0", "dockerhub_digest": "sha256:6602720bc587812d5e2d61aa3dbd212e84d36cdeb957b78f1f3fccee062611e1", "dockerhub_index_digest": "sha256:66aefccd646ac239e9b3f6cec97076b53833ada73318b723a91baac9a76b7dd9", "dockerhub_platform": "linux/amd64", "validation_status": "harbor_validated", "harbor_validation_summary": { "validated_at": "2026-06-20", "local_image": "lolbench/typescript_1:1.0.0", "dockerhub_image": "smartdub26/lolbench:TypeScript_1-1.0.0", "dockerhub_digest": "sha256:86ec21471aef0eff17132a3091c744efc6dddefbe25172e25083ee4414f7b367", "mode_reports": "harbor_validation/TypeScript_1/current_harbor_modes_v2", "mutation_reports": "harbor_validation/TypeScript_1/current_harbor_mutants_v2", "modes": { "aug_post": { "build": "ok", "f2p": { "passed": 3, "total": 3 }, "p2p": { "passed": 2, "total": 2 }, "resolved": true, "error_categories": [] }, "aug_pre": { "build": "ok", "f2p": { "passed": 0, "total": 3 }, "p2p": { "passed": 2, "total": 2 }, "resolved": false, "error_categories": [] }, "orig_post": { "build": "ok", "f2p": { "passed": 13, "total": 13 }, "p2p": { "passed": 50, "total": 50 }, "resolved": true, "error_categories": [] }, "orig_pre": { "build": "ok", "f2p": { "passed": 0, "total": 13 }, "p2p": { "passed": 50, "total": 50 }, "resolved": false, "error_categories": [] }, "union_post": { "build": "ok", "f2p": { "passed": 16, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": true, "error_categories": [] }, "union_pre": { "build": "ok", "f2p": { "passed": 0, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] } }, "mutants": { "total": 10, "killed": 10, "survivors": [], "anomalies": [], "details": [ { "name": "mutant_001_satisfies_returns_target_type", "build": "ok", "f2p": { "passed": 3, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_002_satisfies_skips_target_assignability", "build": "ok", "f2p": { "passed": 9, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_003_no_contextual_type_from_satisfies", "build": "ok", "f2p": { "passed": 9, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_004_satisfies_parsed_as_as_expression", "build": "ok", "f2p": { "passed": 1, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_005_printer_emits_as_keyword_for_satisfies", "build": "ok", "f2p": { "passed": 15, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_006_satisfies_allowed_in_js_files", "build": "ok", "f2p": { "passed": 15, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_007_transformer_leaves_satisfies_in_js_output", "build": "ok", "f2p": { "passed": 2, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_009_for_each_child_skips_satisfies_type", "build": "ok", "f2p": { "passed": 0, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_010_public_visitor_skips_satisfies_type", "build": "ok", "f2p": { "passed": 15, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] }, { "name": "mutant_012_satisfies_keyword_not_offered_in_completions", "build": "ok", "f2p": { "passed": 15, "total": 16 }, "p2p": { "passed": 52, "total": 52 }, "resolved": false, "error_categories": [] } ] } }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3import argparseimport jsonfrom pathlib import Path
def rate(bucket): total = float(bucket.get("total", 0) or 0) if total <= 0: return 0.0 return float(bucket.get("passed", 0) or 0) / total
def write_json(path, payload): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
def main(): parser = argparse.ArgumentParser() parser.add_argument("--suite", default="union") parser.add_argument("--missing-patch") parser.add_argument("--invalid-suite", action="store_true") parser.add_argument("--runner-rc", type=int, default=0) parser.add_argument("agent_report") parser.add_argument("reward_file") args = parser.parse_args()
report_path = Path(args.agent_report) reward_path = Path(args.reward_file)
if args.invalid_suite: reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} sanitized = {"instance_id": "TypeScript_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} write_json(report_path, sanitized) write_json(reward_path, reward) print(f"LoLBench reward=0 invalid suite {args.suite!r}") return 0
if args.missing_patch: reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} sanitized = {"instance_id": "TypeScript_1", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} write_json(report_path, sanitized) write_json(reward_path, reward) print("LoLBench reward=0 missing solution patch") return 0
if not report_path.exists(): reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} write_json(reward_path, reward) print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") return 0
report = json.loads(report_path.read_text()) build_status = report.get("build", {}).get("status") resolved = bool(report.get("resolved")) applied = bool(report.get("applied")) reward = { "reward": 1.0 if resolved else 0.0, "resolved": 1.0 if resolved else 0.0, "applied": 1.0 if applied else 0.0, "build_ok": 1.0 if build_status == "ok" else 0.0, "f2p_pass_rate": rate(report.get("f2p", {})), "p2p_pass_rate": rate(report.get("p2p", {})), "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, } write_json(reward_path, reward) print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) return 0
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243#!/usr/bin/env bashset -euo pipefail
suite=${LOLBENCH_SUITE:-union}mode=${LOLBENCH_MODE:-eval}patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch}private_log=/tmp/lolbench-private-run.log
mkdir -p /logs/verifier /logs/artifacts /in /out
case "$suite" in orig|aug|union) ;; *) python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json exit 0 ;;esac
if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json exit 0fi
if [ "$mode" = "eval" ]; then cp "$patch" /in/solution.patch chmod 0400 /in/solution.patchfi
set +eLOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1runner_rc=$?set -e
cp "$private_log" /logs/verifier/private_run.logif [ -f /out/grader_report.json ]; then cp /out/grader_report.json /logs/verifier/grader_report.jsonfi
python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json
if [ -f /out/agent_report.json ]; then cp /out/agent_report.json /logs/verifier/agent_report.jsonfi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990# LoLBench Harbor Task: TypeScript_2
This is a Harbor-format LoLBench task generated from `TypeScript_PR-54505_Using-and-await-using-declarations`.
Selected source instance:
- Harbor ID: `TypeScript_2`- PR: `microsoft/TypeScript#54505`- Base commit: `d90eb0d731c3f74b131dcfafe69ef5341ed14934`- Test modes: `orig, aug, union`- Default/canonical mode: `union`- Harbor image: `smartdub26/lolbench-linux:TypeScript_2-1.0.0`- Docker Hub image: `smartdub26/lolbench-linux:TypeScript_2-1.0.0`- Docker Hub digest (arm64): `sha256:1291a122c50d1363d03e1ec0cc4061113f7153f02d0c42773cb22479a431a79d`- Docker Hub Linux image (amd64): `smartdub26/lolbench-linux:TypeScript_2-1.0.0`- Docker Hub Linux digest: `sha256:f2bd5e6d40bb6c1a0babeecf6d25e4b11dcbc18e9b17f7ebaa1686f215754cf5`
## Image Setup
Prefer the published Docker Hub image when it is available. Harbor refers tothe image as `smartdub26/lolbench-linux:TypeScript_2-1.0.0`, so Docker can pull itdirectly when it is not present locally:
```bashdocker pull smartdub26/lolbench-linux:TypeScript_2-1.0.0```
Only if the Docker Hub image is unavailable, build the single task imagelocally:
```bashdocker build -t lolbench/typescript_2:1.0.0 harbor_tasks/TypeScript_2/environmentdocker tag lolbench/typescript_2:1.0.0 smartdub26/lolbench-linux:TypeScript_2-1.0.0```
The image contains the processed source tree at the base commit under`/workspace/typescript`. Harbor must not mount a host source checkoutfor the agent.
## Run an Agent
```bash.harbor-venv/bin/harbor run \ -p harbor_tasks/TypeScript_2 \ -a codex \ -m "<model>" \ --job-name TypeScript_2_agent_union \ --jobs-dir harbor_runs/TypeScript_2 \ --no-delete \ --n-concurrent 1 \ --ve LOLBENCH_SUITE=union```
After implementing the requirement, the agent must clean any test-file editsand run:
```bashlolbench-submit```
## Evaluate a Patch
Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, thetask defaults to `union`.
```bashPATCH="$(pwd)/path/to/solution.patch"
.harbor-venv/bin/harbor run \ -p harbor_tasks/TypeScript_2 \ -a oracle \ --job-name TypeScript_2_eval_union \ --jobs-dir harbor_runs/TypeScript_2 \ --no-delete \ --n-concurrent 1 \ --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ --ve LOLBENCH_SUITE=union```
Outputs:
```bashfind harbor_runs/TypeScript_2/TypeScript_2_eval_union -path '*/verifier/agent_report.json' -printfind harbor_runs/TypeScript_2/TypeScript_2_eval_union -path '*/verifier/reward.json' -print```
`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts`tests/`, `tests/private/`, and `solution/` into the separate verifiercontainer; none of those paths are mounted into the agent container.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495# LoLBench eval image: TypeScript PR-54505 (using / await using declarations)# base_commit: d90eb0d731c3f74b131dcfafe69ef5341ed14934# (parent of squash-merge f9cf8216 on main)
ARG BASE_IMAGE=lolbench/typescript-base-node18:1FROM ${BASE_IMAGE}
ARG BASE_COMMIT=d90eb0d731c3f74b131dcfafe69ef5341ed14934
RUN mkdir -p /opt/lolbench/private /in /out /workspace
WORKDIR /workspaceRUN git init typescript && \ cd typescript && \ git remote add origin https://github.com/microsoft/TypeScript.git && \ git fetch --no-tags --depth=1 origin ${BASE_COMMIT} && \ git checkout ${BASE_COMMIT} && \ git ls-files -z > /tmp/typescript-base-files && \ git config user.email lolbench@local && \ git config user.name lolbench && \ if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ fi && \ git tag -f base && git tag -f lolbench-base && \ git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ while read ref; do \ case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ done && \ ( git remote remove origin 2>/dev/null || true ) && \ rm -f .git/FETCH_HEAD && \ git reflog expire --expire=now --all && \ git repack -Ad && \ git prune --expire=now && \ rm /tmp/typescript-base-files && \ git config --global --add safe.directory /workspace/typescript
# TS 5.2-era uses herebyRUN cd /workspace/typescript && \ npm install --no-progress --no-fund --no-audit && \ npx hereby local && \ npx hereby tests
# Harbor runtime adapter: keep the image public/agent-safe.RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fiCOPY metadata.json /opt/lolbench/metadata.jsonCOPY lolbench-submit /usr/local/bin/lolbench-submitCOPY runtime_source_guard.py /usr/local/bin/lolbench-runtime-source-guardCOPY runtime_source_guard_entrypoint.c /tmp/runtime_source_guard_entrypoint.cRUN chmod +x /usr/local/bin/lolbench-submit && \ cc -O2 -Wall -Wextra -o /usr/local/sbin/lolbench-runtime-source-guard-entrypoint /tmp/runtime_source_guard_entrypoint.c && \ rm -f /tmp/runtime_source_guard_entrypoint.c && \ chown root:root /usr/local/bin/lolbench-runtime-source-guard /usr/local/sbin/lolbench-runtime-source-guard-entrypoint && \ chmod 0700 /usr/local/bin/lolbench-runtime-source-guard && \ chmod 4755 /usr/local/sbin/lolbench-runtime-source-guard-entrypoint && \ mkdir -p /home/agent/.pi/agent /home/agent/.cache /home/agent/.config /home/agent/.local && \ chown -R agent:agent /home/agent/.pi /home/agent/.cache /home/agent/.config /home/agent/.local && \ git config --global --add safe.directory /workspace/typescript && \ if [ -d /workspace/typescript/.git ]; then \ cd /workspace/typescript && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ else \ : > /opt/lolbench/base_untracked.txt; \ fi && \ chown -R agent:agent /workspace/typescript /logsENV HOME=/home/agent# Local-reference hardening: retain only the approved base history.RUN git config --system --add safe.directory /workspace/typescript && \ cd /workspace/typescript && \ git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ while read ref; do \ case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ done && \ ( git remote remove origin 2>/dev/null || true ) && \ rm -f .git/FETCH_HEAD && \ git reflog expire --expire=now --all && \ git repack -Ad && \ git prune --expire=now && \ unreachable=$(git fsck --unreachable --no-reflogs) && \ test -z "$unreachable" && \ chown -R agent:agent .git# Keep npm executable but remove cached/global TypeScript and tslib sources.RUN rm -rf /root/.npm /home/agent/.npm && \ rm -f /usr/local/bin/tsc /usr/local/bin/tsserver /usr/bin/tsc /usr/bin/tsserver && \ for p in /usr/local/lib/node_modules /usr/lib/node_modules; do \ if [ -d "$p" ]; then \ find "$p" -mindepth 1 -maxdepth 1 -type d \ \( -iname typescript -o -iname tslib \) -exec rm -rf '{}' +; \ chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; \ fi; \ doneENTRYPOINT ["/usr/local/sbin/lolbench-runtime-source-guard-entrypoint"]USER agentWORKDIR /workspace/typescriptENV LOLBENCH_INSTANCE_ID=TypeScript_2ENV LOLBENCH_SOURCE_SLUG=TypeScript_PR-54505_Using-and-await-using-declarations123services: main: pull_policy: missing123456789101112131415161718192021222324252627282930313233#!/usr/bin/env bashset -euo pipefailexport LC_ALL=C
repo=${1:-$PWD}out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch}
mkdir -p "$(dirname "$out")"cd "$repo"
baseline=/opt/lolbench/base_untracked.txtcurrent=$(mktemp)new_files=$(mktemp)trap 'rm -f "$current" "$new_files"' EXIT
git ls-files --others --exclude-standard | sort > "$current"if [ -f "$baseline" ]; then comm -13 "$baseline" "$current" > "$new_files"else cp "$current" "$new_files"fi
if [ -s "$new_files" ]; then xargs -r git add -N -- < "$new_files"fi
git diff --binary > "$out"
if [ ! -s "$out" ]; then echo "warning: wrote an empty solution patch to $out" >&2else echo "wrote solution patch to $out"fi12345678910111213141516171819202122{ "instance_id": "TypeScript_2", "source_instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", "source_slug": "TypeScript_PR-54505_Using-and-await-using-declarations", "docker_slug": "TypeScript_PR-54505_Using-and-await-using-declarations", "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_2-1.0.0", "project": "TypeScript", "repo": "microsoft/TypeScript", "requirement_doc": "https://github.com/tc39/proposal-explicit-resource-management", "pr_link": "https://github.com/microsoft/TypeScript/pull/54505", "base_commit": "d90eb0d731c3f74b131dcfafe69ef5341ed14934", "merge_commit": "558a5028b785e962e7a26a9d820fc77ca094faf6", "source_history_policy": "ancestors-only", "lolbench_test_modes": [ "orig", "aug", "union" ], "default_lolbench_suite": "union", "canonical_lolbench_suite": "union", "augmentation_available": true}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353#!/usr/bin/env python3"""Remove target-feature reference sources from injected Node agent runtimes.
TypeScript_2 intentionally keeps its base-commit workspace dependencies. Itsworkspace uses tslib 2.5.3, which predates explicit resource management. Someagents, however, install a newer global Node runtime after the container hasstarted. Newer tslib releases include the completed implementations of thetwo disposal helpers targeted by this benchmark.
This guard runs as a root-only sidecar process started by the image entrypoint.It waits for the global npm install to finish, removes npm/source-map caches,replaces only the two target helper bodies with fail-closed stubs, and makesthe injected NVM runtime immutable to the unprivileged agent user."""
from __future__ import annotations
import fcntlimport jsonimport osimport reimport shutilimport statimport sysimport timefrom pathlib import Path
AGENT_HOME = Path("/home/agent")NVM_ROOT = AGENT_HOME / ".nvm"NODE_ROOT_GLOB = "versions/node/*/lib/node_modules"LOCK_PATH = Path("/run/lolbench-runtime-source-guard.lock")READY_PATH = Path("/run/lolbench-runtime-source-guard.ready.json")POLL_SECONDS = 0.05SETTLE_SECONDS = 1.0
CJS_HELPERS = ( ("__addDisposableResource", "env, value, async"), ("__disposeResources", "env"),)
# These are distinctive implementation fragments, not merely public helper# names or signatures already stated in the task instruction.FORBIDDEN_IMPLEMENTATION_FRAGMENTS = ( b"env.stack.pop()", b"An error was suppressed during disposal.", b"Object not disposable.", b"env.stack.push({ value: value, dispose: dispose, async: async })", b"env.stack.push({ async: true })", b"using declarations can only be used with objects", b"function _usingCtx", b"function _dispose(",)
def global_node_roots() -> list[Path]: return sorted(path for path in NVM_ROOT.glob(NODE_ROOT_GLOB) if path.is_dir())
def target_tslib_files(roots: list[Path]) -> list[Path]: files: list[Path] = [] for root in roots: for path in root.glob("**/tslib/tslib.js"): try: data = path.read_bytes() except OSError: continue if b"__addDisposableResource" in data or b"__disposeResources" in data: files.append(path) return sorted(set(files))
def installer_is_running() -> bool: """Return true while a global npm agent install can still be writing."""
for proc in Path("/proc").glob("[0-9]*"): try: command = (proc / "cmdline").read_bytes().replace(b"\0", b" ") process_name = (proc / "comm").read_text(encoding="utf-8").strip() except OSError: continue if process_name.startswith("npm") and b"pi-coding-agent" in command: return True return False
def runtime_install_is_complete(roots: list[Path]) -> bool: """Require npm's final global binary link and Pi entry point."""
for root in roots: package = root / "@earendil-works" / "pi-coding-agent" pi_link = root.parent.parent / "bin" / "pi" if ( (package / "package.json").is_file() and (package / "dist" / "cli.js").is_file() and pi_link.is_symlink() and pi_link.exists() ): return True return False
def stub_cjs_helpers(path: Path) -> int: text = path.read_text(encoding="utf-8") changed = 0 for name, arguments in CJS_HELPERS: pattern = re.compile( rf"(?ms)^ {re.escape(name)} = function \({re.escape(arguments)}\) " rf"\{{.*?^ \}};" ) replacement = ( f" {name} = function () {{\n" ' throw new Error("LOLBENCH_RUNTIME_REFERENCE_REMOVED");\n' " };" ) text, count = pattern.subn(replacement, text) if count == 0 and f"{name} = function ()" in text: continue if count != 1: raise RuntimeError(f"expected one {name} body in {path}, found {count}") changed += count path.write_text(text, encoding="utf-8") return changed
def stub_babel_helpers(roots: list[Path]) -> int: changed = 0 helper_names = ("using", "usingCtx", "dispose") for root in roots: for helper_name in helper_names: paths = set(root.glob(f"**/@babel/runtime/helpers/{helper_name}.js")) paths.update(root.glob(f"**/@babel/runtime/helpers/esm/{helper_name}.js")) for path in sorted(paths): export_name = "_lolbenchRemoved" if "esm" in path.parts: text = ( f"function {export_name}() {{\n" ' throw new Error("LOLBENCH_RUNTIME_REFERENCE_REMOVED");\n' "}\n" f"export {{ {export_name} as default }};\n" ) else: text = ( f"function {export_name}() {{\n" ' throw new Error("LOLBENCH_RUNTIME_REFERENCE_REMOVED");\n' "}\n" f"module.exports = {export_name}, " "module.exports.__esModule = true, " 'module.exports["default"] = module.exports;\n' ) path.write_text(text, encoding="utf-8") changed += 1 return changed
def stub_jiti_babel_helpers(roots: list[Path]) -> int: changed = 0 for root in roots: for path in root.glob("**/jiti/dist/babel.*"): if not path.is_file() or path.suffix == ".map": continue text = path.read_text(encoding="utf-8") file_changed = 0 for helper_name in ("using", "usingCtx", "dispose"): pattern = re.compile( rf"({helper_name}:helper\([^,]+,)" rf"'(?:\\.|[^'\\])*'" rf"(,\{{globals:)" ) replacement = ( rf"\1'function _lolbenchRemoved(){{throw new Error(" '"LOLBENCH_RUNTIME_REFERENCE_REMOVED")}'"'" rf"\2" ) text, count = pattern.subn(replacement, text) if count == 0 and "LOLBENCH_RUNTIME_REFERENCE_REMOVED" in text: continue if count != 1: raise RuntimeError( f"expected one serialized {helper_name} helper in {path}, " f"found {count}" ) file_changed += count path.write_text(text, encoding="utf-8") changed += file_changed return changed
def remove_nonruntime_sources(roots: list[Path], tslib_files: list[Path]) -> int: removed = 0 for root in roots: for pattern in ("*.map", "*.d.ts", "*.d.mts", "*.d.cts"): for path in root.glob(f"**/{pattern}"): try: path.unlink() except FileNotFoundError: continue removed += 1 for tslib_file in tslib_files: tslib_dir = tslib_file.parent for name in ( "tslib.es6.js", "tslib.es6.mjs", "tslib.es6.html", "tslib.html", "README.md", "SECURITY.md", ): path = tslib_dir / name try: path.unlink() except FileNotFoundError: continue removed += 1 return removed
def assert_no_reference_implementation(roots: list[Path]) -> int: scanned = 0 for root in roots: for path in root.glob("**/*"): if not path.is_file() or path.is_symlink(): continue try: if path.stat().st_size > 32 * 1024 * 1024: continue data = path.read_bytes() except OSError: continue scanned += 1 for fragment in FORBIDDEN_IMPLEMENTATION_FRAGMENTS: if fragment in data: raise RuntimeError(f"reference implementation remains in {path}") return scanned
def remove_agent_caches() -> None: for path in (AGENT_HOME / ".npm", AGENT_HOME / ".cache" / "node-gyp"): shutil.rmtree(path, ignore_errors=True)
def root_lock_tree(path: Path) -> None: """Make a tree readable/executable but not replaceable by the agent."""
for current_root, directories, files in os.walk(path, topdown=False): current = Path(current_root) for name in files: item = current / name try: if item.is_symlink(): os.lchown(item, 0, 0) continue mode = stat.S_IMODE(item.stat().st_mode) os.chown(item, 0, 0) os.chmod(item, mode & ~(stat.S_IWGRP | stat.S_IWOTH)) except FileNotFoundError: continue for name in directories: item = current / name try: if item.is_symlink(): os.lchown(item, 0, 0) continue mode = stat.S_IMODE(item.stat().st_mode) os.chown(item, 0, 0) os.chmod(item, mode & ~(stat.S_IWGRP | stat.S_IWOTH)) except FileNotFoundError: continue mode = stat.S_IMODE(path.stat().st_mode) os.chown(path, 0, 0) os.chmod(path, mode & ~(stat.S_IWGRP | stat.S_IWOTH))
def sanitize_once() -> bool: roots = global_node_roots() tslib_files = target_tslib_files(roots) if ( not roots or not tslib_files or installer_is_running() or not runtime_install_is_complete(roots) ): return False
helper_bodies = sum(stub_cjs_helpers(path) for path in tslib_files) helper_bodies += stub_babel_helpers(roots) helper_bodies += stub_jiti_babel_helpers(roots) removed_files = remove_nonruntime_sources(roots, tslib_files) remove_agent_caches() scanned_files = assert_no_reference_implementation(roots)
root_lock_tree(NVM_ROOT) os.chown(AGENT_HOME, 0, 0) os.chmod(AGENT_HOME, 0o1777)
report = { "instance_id": "TypeScript_2", "status": "sanitized", "global_node_roots": [os.fspath(path) for path in roots], "tslib_runtime_files": [os.fspath(path) for path in tslib_files], "stubbed_helper_bodies": helper_bodies, "removed_nonruntime_files": removed_files, "scanned_runtime_files": scanned_files, "npm_cache_removed": not (AGENT_HOME / ".npm").exists(), "nvm_root_owned": NVM_ROOT.stat().st_uid == 0, } temporary = READY_PATH.with_suffix(".tmp") temporary.write_text(json.dumps(report, indent=2, sort_keys=True) + "\n") os.chmod(temporary, 0o444) temporary.replace(READY_PATH) return True
def main() -> int: if os.geteuid() != 0: print("runtime source guard must run as root", file=sys.stderr) return 1
LOCK_PATH.parent.mkdir(parents=True, exist_ok=True) with LOCK_PATH.open("w") as lock: try: fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB) except BlockingIOError: return 0
candidate_since: float | None = None while True: try: if READY_PATH.is_file(): time.sleep(1.0) continue roots = global_node_roots() ready_to_sanitize = ( bool(roots) and bool(target_tslib_files(roots)) and runtime_install_is_complete(roots) and not installer_is_running() ) if not ready_to_sanitize: candidate_since = None elif candidate_since is None: candidate_since = time.monotonic() elif time.monotonic() - candidate_since >= SETTLE_SECONDS: sanitize_once() except Exception: # Do not expose implementation-matching diagnostics to the # agent. The missing ready marker makes validation fail closed. pass time.sleep(POLL_SECONDS)
if __name__ == "__main__": raise SystemExit(main())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162#define _GNU_SOURCE
#include <errno.h>#include <fcntl.h>#include <grp.h>#include <stdio.h>#include <stdlib.h>#include <sys/stat.h>#include <sys/types.h>#include <unistd.h>
static void start_guard(void) { pid_t pid = fork(); if (pid != 0) { return; }
if (setgid(0) != 0 || setuid(0) != 0 || setsid() < 0) { _exit(125); }
int null_fd = open("/dev/null", O_RDWR); if (null_fd >= 0) { dup2(null_fd, STDIN_FILENO); dup2(null_fd, STDOUT_FILENO); dup2(null_fd, STDERR_FILENO); if (null_fd > STDERR_FILENO) { close(null_fd); } }
execl( "/usr/local/bin/lolbench-runtime-source-guard", "lolbench-runtime-source-guard", (char *)NULL ); _exit(126);}
int main(int argc, char **argv) { uid_t real_uid = getuid(); gid_t real_gid = getgid();
if (geteuid() == 0) { start_guard(); if (real_uid != 0) { if (setgroups(0, NULL) != 0 || setgid(real_gid) != 0 || setuid(real_uid) != 0) { perror("failed to drop entrypoint privileges"); return 125; } } }
if (argc < 2) { execl("/bin/bash", "bash", (char *)NULL); } else { execvp(argv[1], &argv[1]); } perror("failed to execute container command"); return errno == ENOENT ? 127 : 126;}1234567{ "source_policy": "dockerfile_fetch_pruned_ancestor_history", "local_reference_policy": "post_start_agent_runtime_tslib_babel_guarded", "base_commit": "d90eb0d731c3f74b131dcfafe69ef5341ed14934", "repo": "microsoft/TypeScript", "note": "The Dockerfile fetches only the declared base history, removes refs/remotes/reflogs, repacks and prunes unreachable objects, and asserts that git fsck finds no unreachable object. It removes cached/global TypeScript and tslib sources at build time. A root-only entrypoint sidecar waits for the injected Pi npm runtime, removes maps and type sources, stubs target tslib/Babel helper implementations, removes npm caches, scans for reference fragments, and root-locks the NVM tree before the adapter continues."}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824You are working in `/workspace/typescript`, a source tree checked out atthe base commit for this task. Implement the requested behavior in the sourcetree, then run:
```bashlolbench-submit```
Do not stop after editing files, running tests, or describing the solution. Thetask is complete only when `lolbench-submit` has created`/logs/artifacts/solution.patch`. If that file does not exist, continueworking and run `lolbench-submit` again.
That command writes your implementation diff to`/logs/artifacts/solution.patch`, which is the artifact the Harbor verifierwill grade. Before running `lolbench-submit`, clean or revert any test filesyou created or modified; test files must not be included in the final`solution.patch`.
This environment has no outbound internet access — `curl`/`wget`, `git fetch`/`clone`, package installs, and web fetch/search will all fail. Implement the requirements using only the code already in the workspace and your own knowledge; do not attempt to fetch or search external resources.
Now please implement the following requirements in the source tree:
---
# ECMAScript Explicit Resource Management
> **NOTE:** This proposal has subsumed the [Async Explicit Resource Management](https://github.com/tc39/proposal-async-explicit-resource-management)> proposal. This proposal repository should be used for further discussion of both sync and async of explicit resource> management.
This proposal intends to address a common pattern in software development regardingthe lifetime and management of various resources (memory, I/O, etc.). This patterngenerally includes the allocation of a resource and the ability to explicitlyrelease critical resources.
For example, ECMAScript Generator Functions and Async Generator Functions expose this pattern through the`return` method, as a means to explicitly evaluate `finally` blocks to ensureuser-defined cleanup logic is preserved:
```js// sync generatorsfunction * g() { const handle = acquireFileHandle(); // critical resource try { ... } finally { handle.release(); // cleanup }}
const obj = g();try { const r = obj.next(); ...}finally { obj.return(); // calls finally blocks in `g`}```
```js// async generatorsasync function * g() { const handle = acquireStream(); // critical resource try { ... } finally { await stream.close(); // cleanup }}
const obj = g();try { const r = await obj.next(); ...}finally { await obj.return(); // calls finally blocks in `g`}```
As such, we propose the adoption of a novel syntax to simplify this common pattern:
```js// sync disposalfunction * g() { using handle = acquireFileHandle(); // block-scoped critical resource} // cleanup
{ using obj = g(); // block-scoped declaration const r = obj.next();} // calls finally blocks in `g````
```js// async disposalasync function * g() { using stream = acquireStream(); // block-scoped critical resource ...} // cleanup
{ await using obj = g(); // block-scoped declaration const r = await obj.next();} // calls finally blocks in `g````
In addition, we propose the addition of two disposable container objects to assistwith managing multiple resources:
- `DisposableStack` — A stack-based container of disposable resources.- `AsyncDisposableStack` — A stack-based container of asynchronously disposable resources.
# Motivations
This proposal is motivated by a number of cases:
- Inconsistent patterns for resource management: - ECMAScript Iterators: `iterator.return()` - WHATWG Stream Readers: `reader.releaseLock()` - NodeJS FileHandles: `handle.close()` - Emscripten C++ objects handles: `Module._free(ptr) obj.delete() Module.destroy(obj)`- Avoiding common footguns when managing resources: ```js const reader = stream.getReader(); ... reader.releaseLock(); // Oops, should have been in a try/finally ```- Scoping resources: ```js const handle = ...; try { ... // ok to use `handle` } finally { handle.close(); } // not ok to use `handle`, but still in scope ```- Avoiding common footguns when managing multiple resources: ```js const a = ...; const b = ...; try { ... } finally { a.close(); // Oops, issue if `b.close()` depends on `a`. b.close(); // Oops, `b` never reached if `a.close()` throws. } ```- Avoiding lengthy code when managing multiple resources correctly: ```js // sync disposal { // block avoids leaking `a` or `b` to outer scope const a = ...; try { const b = ...; try { ... } finally { b.close(); // ensure `b` is closed before `a` in case `b` // depends on `a` } } finally { a.close(); // ensure `a` is closed even if `b.close()` throws } } // both `a` and `b` are out of scope ``` Compared to: ```js // avoids leaking `a` or `b` to outer scope // ensures `b` is disposed before `a` in case `b` depends on `a` // ensures `a` is disposed even if disposing `b` throws using a = ..., b = ...; ... ``` ```js // async sync disposal { // block avoids leaking `a` or `b` to outer scope const a = ...; try { const b = ...; try { ... } finally { await b.close(); // ensure `b` is closed before `a` in case `b` // depends on `a` } } finally { await a.close(); // ensure `a` is closed even if `b.close()` throws } } // both `a` and `b` are out of scope ``` Compared to: ```js // avoids leaking `a` or `b` to outer scope // ensures `b` is disposed before `a` in case `b` depends on `a` // ensures `a` is disposed even if disposing `b` throws await using a = ..., b = ...; ... ```- Non-blocking memory/IO applications: ```js import { ReaderWriterLock } from "..."; const lock = new ReaderWriterLock();
export async function readData() { // wait for outstanding writer and take a read lock using lockHandle = await lock.read(); ... // any number of readers await ...; ... // still in read lock after `await` } // release the read lock
export async function writeData(data) { // wait for all readers and take a write lock using lockHandle = await lock.write(); ... // only one writer await ...; ... // still in write lock after `await` } // release the write lock ```- Potential for use with the [Fixed Layout Objects Proposal](https://github.com/tc39/proposal-structs) and `shared struct`: ```js // main.js shared struct class SharedData { ready = false; processed = false; }
const worker = new Worker('worker.js'); const m = new Atomics.Mutex(); const cv = new Atomics.ConditionVariable(); const data = new SharedData(); worker.postMessage({ m, cv, data });
// send data to worker { // wait until main can get a lock on 'm' using lck = m.lock();
// mark data for worker data.ready = true; console.log("main is ready");
} // unlocks 'm'
// notify potentially waiting worker cv.notifyOne();
{ // reacquire lock on 'm' using lck = m.lock();
// release the lock on 'm' and wait for the worker to finish processing cv.wait(m, () => data.processed);
} // unlocks 'm' ```
```js // worker.js onmessage = function (e) { const { m, cv, data } = e.data;
{ // wait until worker can get a lock on 'm' using lck = m.lock();
// release the lock on 'm' and wait until main() sends data cv.wait(m, () => data.ready);
// after waiting we once again own the lock on 'm' console.log("worker thread is processing data");
// send data back to main data.processed = true; console.log("worker thread is done");
} // unlocks 'm' } ```
# Prior Art
- C#: - [`using` statement](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement) - [`using` declaration](https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/proposals/csharp-8.0/using#using-declaration)- Java: [`try`-with-resources statement](https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html)- Python: [`with` statement](https://docs.python.org/3/reference/compound_stmts.html#the-with-statement)
# Definitions
- _Resource_ — An object with a specific lifetime, at the end of which either a lifetime-sensitive operation should be performed or a non-garbage-collected reference (such as a file handle, socket, etc.) should be closed or freed.- _Resource Management_ — A process whereby "resources" are released, triggering any lifetime-sensitive operations or freeing any related non-garbage-collected references.- _Implicit Resource Management_ — Indicates a system whereby the lifetime of a "resource" is managed implicitly by the runtime as part of garbage collection, such as: - `WeakMap` keys - `WeakSet` values - `WeakRef` values - `FinalizationRegistry` entries- _Explicit Resource Management_ — Indicates a system whereby the lifetime of a "resource" is managed explicitly by the user either **imperatively** (by directly calling a method like `Symbol.dispose`) or **declaratively** (through a block-scoped declaration like `using`).
# Syntax
## `using` Declarations
```js// a synchronously-disposed, block-scoped resourceusing x = expr1; // resource w/ local bindingusing y = expr2, z = expr4; // multiple resources```
# Grammar
Please refer to the [specification text][Specification] for the most recent version of the grammar.
## `await using` Declarations
```js// an asynchronously-disposed, block-scoped resourceawait using x = expr1; // resource w/ local bindingawait using y = expr2, z = expr4; // multiple resources```
An `await using` declaration can appear in the following contexts:- The top level of a _Module_ anywhere _VariableStatement_ is allowed, as long as it is not immediately nested inside of a _CaseClause_ or _DefaultClause_.- In the body of an async function or async generator anywhere a _VariableStatement_ is allowed, as long as it is not immediately nested inside of a _CaseClause_ or _DefaultClause_.- In the head of a `for-of` or `for-await-of` statement.
## `await using` in `for-of` and `for-await-of` Statements
```jsfor (await using x of y) ...
for await (await using x of y) ...```
You can use an `await using` declaration in a `for-of` or `for-await-of` statement inside of an async context toexplicitly bind each iterated value as an async disposable resource. `for-await-of` does not implicitly make a non-async`using` declaration into an async `await using` declaration, as the `await` markers in `for-await-of` and `await using`are explicit indicators for distinct cases: `for await` *only* indicates async iteration, while `await using` *only*indicates async disposal. For example:
```js
// sync iteration, sync disposalfor (using x of y) ; // no implicit `await` at end of each iteration
// sync iteration, async disposalfor (await using x of y) ; // implicit `await` at end of each iteration
// async iteration, sync disposalfor await (using x of y) ; // implicit `await` at end of each iteration
// async iteration, async disposalfor await (await using x of y) ; // implicit `await` at end of each iteration```
While there is some overlap in that the last three cases introduce some form of implicit `await` during execution, itis intended that the presence or absence of the `await` modifier in a `using` declaration is an explicit indicator as towhether we are expecting the iterated value to have an `@@asyncDispose` method. This distinction is in line with thebehavior of `for-of` and `for-await-of`:
```jsconst iter = { [Symbol.iterator]() { return [].values(); } };const asyncIter = { [Symbol.asyncIterator]() { return [].values(); } };
for (const x of iter) ; // ok: `iter` has @@iteratorfor (const x of asyncIter) ; // throws: `asyncIter` does not have @@iterator
for await (const x of iter) ; // ok: `iter` has @@iterator (fallback)for await (const x of asyncIter) ; // ok: `asyncIter` has @@asyncIterator
```
`using` and `await using` have the same distinction:
```jsconst res = { [Symbol.dispose]() {} };const asyncRes = { [Symbol.asyncDispose]() {} };
using x = res; // ok: `res` has @@disposeusing x = asyncRes; // throws: `asyncRes` does not have @@dispose
await using x = res; // ok: `res` has @@dispose (fallback)await using x = asyncres; // ok: `asyncRes` has @@asyncDispose```
This results in a matrix of behaviors based on the presence of each `await` marker:
```jsconst res = { [Symbol.dispose]() {} };const asyncRes = { [Symbol.asyncDispose]() {} };const iter = { [Symbol.iterator]() { return [res, asyncRes].values(); } };const asyncIter = { [Symbol.asyncIterator]() { return [res, asyncRes].values(); } };
for (using x of iter) ;// sync iteration, sync disposal// - `iter` has @@iterator: ok// - `res` has @@dispose: ok// - `asyncRes` does not have @@dispose: *error*
for (using x of asyncIter) ;// sync iteration, sync disposal// - `asyncIter` does not have @@iterator: *error*
for (await using x of iter) ;// sync iteration, async disposal// - `iter` has @@iterator: ok// - `res` has @@dispose (fallback): ok// - `asyncRes` has @@asyncDispose: ok
for (await using x of asyncIter) ;// sync iteration, async disposal// - `asyncIter` does not have @@iterator: error
for await (using x of iter) ;// async iteration, sync disposal// - `iter` has @@iterator (fallback): ok// - `res` has @@dispose: ok// - `asyncRes` does not have @@dispose: error
for await (using x of asyncIter) ;// async iteration, sync disposal// - `asyncIter` has @@asyncIterator: ok// - `res` has @@dispose: ok// - `asyncRes` does not have @@dispose: error
for await (await using x of iter) ;// async iteration, async disposal// - `iter` has @@iterator (fallback): ok// - `res` has @@dispose (fallback): ok// - `asyncRes` does has @@asyncDispose: ok
for await (await using x of asyncIter) ;// async iteration, async disposal// - `asyncIter` has @@asyncIterator: ok// - `res` has @@dispose (fallback): ok// - `asyncRes` does has @@asyncDispose: ok```
Or, in table form:
| Syntax | Iteration | Disposal ||:---------------------------------|:------------------------------:|:----------------------------:|| `for (using x of y)` | `@@iterator` | `@@dispose` || `for (await using x of y)` | `@@iterator` | `@@asyncDispose`/`@@dispose` || `for await (using x of y)` | `@@asyncIterator`/`@@iterator` | `@@dispose` || `for await (await using x of y)` | `@@asyncIterator`/`@@iterator` | `@@asyncDispose`/`@@dispose` |
# Semantics
## `using` Declarations
### `using` Declarations with Explicit Local Bindings
```grammarkdownUsingDeclaration : `using` BindingList `;`
LexicalBinding : BindingIdentifier Initializer```
When a `using` declaration is parsed with _BindingIdentifier_ _Initializer_, the bindings created in the declarationare tracked for disposal at the end of the containing _Block_ or _Module_ (a `using` declaration cannot be usedat the top level of a _Script_):
```js{ ... // (1) using x = expr1; ... // (2)}```
Internally, the TypeScript parser marks a `using` declaration list with the `NodeFlags.Using` flag (defined as `1 << 2`) and an `await using` declaration list with `NodeFlags.AwaitUsing`, defined as the combination `Const | Using`. Both are folded into the block-scoped and constant flag groups — `BlockScoped` is `Let | Const | Using` and `Constant` is `Const | Using` — so a `using` or `await using` binding is block-scoped and, like a `const`, immutable; reassigning one is an error.
The above example has similar runtime semantics as the following transposed representation:
```js{ const $$try = { stack: [], error: undefined, hasError: false }; try { ... // (1)
const x = expr1; if (x !== null && x !== undefined) { const $$dispose = x[Symbol.dispose]; if (typeof $$dispose !== "function") { throw new TypeError(); } $$try.stack.push({ value: x, dispose: $$dispose }); }
... // (2) } catch ($$error) { $$try.error = $$error; $$try.hasError = true; } finally { while ($$try.stack.length) { const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); try { $$dispose.call($$expr); } catch ($$error) { $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; $$try.hasError = true; } } if ($$try.hasError) { throw $$try.error; } }}```
If exceptions are thrown both in the block following the `using` declaration and in the call to`[Symbol.dispose]()`, all exceptions are reported.
In the TypeScript compiler this transposition is not inlined at each declaration site as shown above. When a `using` declaration is downleveled for an output target that lacks native support, the transform routes the logic through two named runtime helpers, `__addDisposableResource` and `__disposeResources`. `__addDisposableResource(env, value, async)` records a single resource — resolving the value's `[Symbol.asyncDispose]` method when `async` is `true` (falling back to `[Symbol.dispose]`) and its `[Symbol.dispose]` method otherwise; a `using` declaration passes `async` as `false`, while an `await using` declaration passes it as `true`. `__disposeResources(env)` then disposes the recorded resources in reverse order when the block exits. When a disposer throws while another error is already pending, it combines them as `new SuppressedError(error, suppressed, "An error was suppressed during disposal.")`, using that exact string as the default message for a disposal-suppressed error, and rethrows once the remaining resources have been disposed.
### `using` Declarations with Multiple Resources
A `using` declaration can mix multiple explicit bindings in the same declaration:
```js{ ... using x = expr1, y = expr2; ...}```
These bindings are again used to perform resource disposal when the _Block_ or _Module_ exits, however in this case`[Symbol.dispose]()` is invoked in the reverse order of their declaration. This is _approximately_ equivalent to thefollowing:
```js{ ... // (1) using x = expr1; using y = expr2; ... // (2)}```
Both of the above cases would have similar runtime semantics as the following transposed representation:
```js{ const $$try = { stack: [], error: undefined, hasError: false }; try { ... // (1)
const x = expr1; if (x !== null && x !== undefined) { const $$dispose = x[Symbol.dispose]; if (typeof $$dispose !== "function") { throw new TypeError(); } $$try.stack.push({ value: x, dispose: $$dispose }); }
const y = expr2; if (y !== null && y !== undefined) { const $$dispose = y[Symbol.dispose]; if (typeof $$dispose !== "function") { throw new TypeError(); } $$try.stack.push({ value: y, dispose: $$dispose }); }
... // (2) } catch ($$error) { $$try.error = $$error; $$try.hasError = true; } finally { while ($$try.stack.length) { const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); try { $$dispose.call($$expr); } catch ($$error) { $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; $$try.hasError = true; } } if ($$try.hasError) { throw $$try.error; } }}```
Since we must always ensure that we properly release resources, we must ensure that any abrupt completion that mightoccur during binding initialization results in evaluation of the cleanup step. When there are multiple declarations inthe list, we track each resource in the order they are declared. As a result, we must release these resources in reverseorder.
### `using` Declarations and `null` or `undefined` Values
This proposal has opted to ignore `null` and `undefined` values provided to the `using` declarations. This is similar tothe behavior of `using` in C#, which also allows `null`. One primary reason for this behavior is to simplify a commoncase where a resource might be optional, without requiring duplication of work or needless allocations:
```jsif (isResourceAvailable()) { using resource = getResource(); ... // (1) resource.doSomething() ... // (2)}else { // duplicate code path above ... // (1) above ... // (2) above}```
Compared to:
```jsusing resource = isResourceAvailable() ? getResource() : undefined;... // (1) do some work with or without resourceresource?.doSomething();... // (2) do some other work with or without resource```
### `using` Declarations and Values Without `[Symbol.dispose]`
If a resource does not have a callable `[Symbol.dispose]` member, a `TypeError` would be thrown **immediately** when theresource is tracked.
### `using` Declarations in `for-of` and `for-await-of` Loops
A `using` declaration _may_ occur in the _ForDeclaration_ of a `for-of` or `for-await-of` loop:
```jsfor (using x of iterateResources()) { // use x}```
In this case, the value bound to `x` in each iteration will be _synchronously_ disposed at the end of each iteration.This will not dispose resources that are not iterated, such as if iteration is terminated early due to `return`,`break`, or `throw`.
`using` declarations _may not_ be used in in the head of a `for-in` loop.
## `await using` Declarations
### `await using` Declarations with Explicit Local Bindings
```grammarkdownUsingDeclaration : `await` `using` BindingList `;`
LexicalBinding : BindingIdentifier Initializer```
When an `await using` declaration is parsed with _BindingIdentifier_ _Initializer_, the bindings created in thedeclaration are tracked for disposal at the end of the containing async function body, _Block_, or _Module_:
```js{ ... // (1) await using x = expr1; ... // (2)}```
The above example has similar runtime semantics as the following transposed representation:
```js{ const $$try = { stack: [], error: undefined, hasError: false }; try { ... // (1)
const x = expr1; if (x !== null && x !== undefined) { let $$dispose = x[Symbol.asyncDispose]; if (typeof $$dispose !== "function") { $$dispose = x[Symbol.dispose]; } if (typeof $$dispose !== "function") { throw new TypeError(); } $$try.stack.push({ value: x, dispose: $$dispose }); }
... // (2) } catch ($$error) { $$try.error = $$error; $$try.hasError = true; } finally { while ($$try.stack.length) { const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); try { await $$dispose.call($$expr); } catch ($$error) { $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; $$try.hasError = true; } } if ($$try.hasError) { throw $$try.error; } }}```
If exceptions are thrown both in the statements following the `await using` declaration and in the call to`[Symbol.asyncDispose]()`, all exceptions are reported.
### `await using` Declarations with Multiple Resources
An `await using` declaration can mix multiple explicit bindings in the same declaration:
```js{ ... await using x = expr1, y = expr2; ...}```
These bindings are again used to perform resource disposal when the _Block_ or _Module_ exits, however in this case eachresource's `[Symbol.asyncDispose]()` is invoked in the reverse order of their declaration. This is _approximately_equivalent to the following:
```js{ ... // (1) await using x = expr1; await using y = expr2; ... // (2)}```
Both of the above cases would have similar runtime semantics as the following transposed representation:
```js{ const $$try = { stack: [], error: undefined, hasError: false }; try { ... // (1)
const x = expr1; if (x !== null && x !== undefined) { let $$dispose = x[Symbol.asyncDispose]; if (typeof $$dispose !== "function") { $$dispose = x[Symbol.dispose]; } if (typeof $$dispose !== "function") { throw new TypeError(); } $$try.stack.push({ value: x, dispose: $$dispose }); }
const y = expr2; if (y !== null && y !== undefined) { let $$dispose = y[Symbol.asyncDispose]; if (typeof $$dispose !== "function") { $$dispose = y[Symbol.dispose]; } if (typeof $$dispose !== "function") { throw new TypeError(); } $$try.stack.push({ value: y, dispose: $$dispose }); }
... // (2) } catch ($$error) { $$try.error = $$error; $$try.hasError = true; } finally { while ($$try.stack.length) { const { value: $$expr, dispose: $$dispose } = $$try.stack.pop(); try { await $$dispose.call($$expr); } catch ($$error) { $$try.error = $$try.hasError ? new SuppressedError($$error, $$try.error) : $$error; $$try.hasError = true; } } if ($$try.hasError) { throw $$try.error; } }}```
Since we must always ensure that we properly release resources, we must ensure that any abrupt completion that mightoccur during binding initialization results in evaluation of the cleanup step. When there are multiple declarations inthe list, we track each resource in the order they are declared. As a result, we must release these resources in reverseorder.
### `await using` Declarations and `null` or `undefined` Values
This proposal has opted to ignore `null` and `undefined` values provided to `await using` declarations. This isconsistent with the proposed behavior for the `using` declarations in this proposal. Like in the sync case, this allowssimplifying a common case where a resource might be optional, without requiring duplication of work or needlessallocations:
```jsif (isResourceAvailable()) { await using resource = getResource(); ... // (1) resource.doSomething() ... // (2)}else { // duplicate code path above ... // (1) above ... // (2) above}```
Compared to:
```jsawait using resource = isResourceAvailable() ? getResource() : undefined;... // (1) do some work with or without resourceresource?.doSomething();... // (2) do some other work with or without resource```
### `await using` Declarations and Values Without `[Symbol.asyncDispose]` or `[Symbol.dispose]`
If a resource does not have a callable `[Symbol.asyncDispose]` or `[Symbol.asyncDispose]` member, a `TypeError` would be thrown **immediately** when the resource is tracked.
### `await using` Declarations in `for-of` and `for-await-of` Loops
An `await using` declaration _may_ occur in the _ForDeclaration_ of a `for-await-of` loop:
```jsfor await (await using x of iterateResources()) { // use x}```
In this case, the value bound to `x` in each iteration will be _asynchronously_ disposed at the end of each iteration.This will not dispose resources that are not iterated, such as if iteration is terminated early due to `return`,`break`, or `throw`.
`await using` declarations _may not_ be used in in the head of a `for-of` or `for-in` loop.
### Implicit Async Interleaving Points ("implicit `await`")
The `await using` syntax introduces an implicit async interleaving point (i.e., an implicit `await`) whenever controlflow exits an async function body, _Block_, or _Module_ containing an `await using` declaration. This means that twostatements that currently execute in the same microtask, such as:
```jsasync function f() { { a(); } // exit block b(); // same microtask as call to `a()`}```
will instead execute in different microtasks if an `await using` declaration is introduced:
```jsasync function f() { { await using x = ...; a(); } // exit block, implicit `await` b(); // different microtask from call to `a()`.}```
It is important that such an implicit interleaving point be adequately indicated within the syntax. We believe thatthe presence of `await using` within such a block is an adequate indicator, since it should be fairly easy to recognizea _Block_ containing an `await using` statement in well-formatted code.
It is also feasible for editors to use features such as syntax highlighting, editor decorations, and inlay hints tofurther highlight such transitions, without needing to specify additional syntax.
Further discussion around the `await using` syntax and how it pertains to implicit async interleaving points can befound in [#1](https://github.com/tc39/proposal-async-explicit-resource-management/issues/1).
# Examples
The following show examples of using this proposal with various APIs, assuming those APIs adopted this proposal.
### WHATWG Streams API```js{ using reader = stream.getReader(); const { value, done } = reader.read();} // 'reader' is disposed```
### NodeJS FileHandle```js{ using f1 = await fs.promises.open(s1, constants.O_RDONLY), f2 = await fs.promises.open(s2, constants.O_WRONLY); const buffer = Buffer.alloc(4092); const { bytesRead } = await f1.read(buffer); await f2.write(buffer, 0, bytesRead);} // 'f2' is disposed, then 'f1' is disposed```
### NodeJS Streams```js{ await using writable = ...; writable.write(...);} // 'writable.end()' is called and its result is awaited```
### Logging and tracing```js// audit privileged function call entry and exitfunction privilegedActivity() { using activity = auditLog.startActivity("privilegedActivity"); // log activity start ...} // log activity end```
### Async Coordination```jsimport { Semaphore } from "...";const sem = new Semaphore(1); // allow one participant at a time
export async function tryUpdate(record) { using lck = await sem.wait(); // asynchronously block until we are the sole participant ...} // synchronously release semaphore and notify the next participant```
### Three-Phase Commit Transactions```js// roll back transaction if either action failsasync function transfer(account1, account2) { await using tx = transactionManager.startTransaction(account1, account2); await account1.debit(amount); await account2.credit(amount);
// mark transaction success if we reach this point tx.succeeded = true;} // await transaction commit or rollback```
### Shared Structs**main_thread.js**```js// main_thread.jsshared struct Data { mut; cv; ready = 0; processed = 0; // ...}
const data = Data();data.mut = Atomics.Mutex();data.cv = Atomics.ConditionVariable();
// start two workersstartWorker1(data);startWorker2(data);```
**worker1.js**```jsconst data = ...;const { mut, cv } = data;
{ // lock mutex using lck = Atomics.Mutex.lock(mut);
// NOTE: at this point we currently own the lock
// load content into data and signal we're ready // ... Atomics.store(data, "ready", 1);
} // release mutex
// NOTE: at this point we no longer own the lock
// notify worker 2 that it should wakeAtomics.ConditionVariable.notifyOne(cv);
{ // reacquire lock on mutex using lck = Atomics.Mutex.lock(mut);
// NOTE: at this point we currently own the lock
// release mutex and wait until condition is met to reacquire it Atomics.ConditionVariable.wait(mut, () => Atomics.load(data, "processed") === 1);
// NOTE: at this point we currently own the lock
// Do something with the processed data // ...
} // release mutex
// NOTE: at this point we no longer own the lock```
**worker2.js**```jsconst data = ...;const { mut, cv } = data;
{ // lock mutex using lck = Atomics.Mutex.lock(mut);
// NOTE: at this point we currently own the lock
// release mutex and wait until condition is met to reacquire it Atomics.ConditionVariable.wait(mut, () => Atomics.load(data, "ready") === 1);
// NOTE: at this point we currently own the lock
// read in values from data, perform our processing, then indicate we are done // ... Atomics.store(data, "processed", 1);
} // release mutex
// NOTE: at this point we no longer own the lock```
# API
## Additions to `Symbol`
This proposal adds the `dispose` and `asyncDispose` properties to the `Symbol` constructor, whose values are the`@@dispose` and `@@asyncDispose` internal symbols:
**Well-known Symbols**| Specification Name | \[\[Description]] | Value and Purpose ||:-|:-|:-|| _@@dispose_ | *"Symbol.dispose"* | A method that explicitly disposes of resources held by the object. Called by the semantics of `using` declarations and by `DisposableStack` objects. || _@@asyncDispose_ | *"Symbol.asyncDispose"* | A method that asynchronosly explicitly disposes of resources held by the object. Called by the semantics of `await using` declarations and by `AsyncDisposableStack` objects. |
**TypeScript Definition**```tsinterface SymbolConstructor { readonly asyncDispose: unique symbol; readonly dispose: unique symbol;}```
## The `SuppressedError` Error
If an exception occurs during resource disposal, it is possible that it might suppress an existing exception thrownfrom the body, or from the disposal of another resource. Languages like Java allow you to access a suppressed exceptionvia a [`getSuppressed()`](https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#getSuppressed()) method onthe exception. However, ECMAScript allows you to throw any value, not just `Error`, so there is no convenient place toattach a suppressed exception. To better surface these suppressed exceptions and support both logging and errorrecovery, this proposal seeks to introduce a new `SuppressedError` built-in `Error` subclass which would contain boththe error that was most recently thrown, as well as the error that was suppressed:
```jsclass SuppressedError extends Error { /** * Wraps an error that suppresses another error, and the error that was suppressed. * @param {*} error The error that resulted in a suppression. * @param {*} suppressed The error that was suppressed. * @param {string} message The message for the error. * @param {{ cause?: * }} [options] Options for the error. */ constructor(error, suppressed, message, options);
/** * The name of the error (i.e., `"SuppressedError"`). * @type {string} */ name = "SuppressedError";
/** * The error that resulted in a suppression. * @type {*} */ error;
/** * The error that was suppressed. * @type {*} */ suppressed;
/** * The message for the error. * @type {*} */ message;}```
We've chosen to use `SuppressedError` over `AggregateError` for several reasons:- `AggregateError` is designed to hold a list of multiple errors, with no correlation between those errors, while `SuppressedError` is intended to hold references to two errors with a direct correlation.- `AggregateError` is intended to ideally hold a flat list of errors. `SuppressedError` is intended to hold a jagged set of errors (i.e., `e.suppressed.suppressed.suppressed` if there were successive error suppressions).- The only error correlation on `AggregateError` is through `cause`, however a `SuppressedError` isn't "caused" by the error it suppresses. In addition, `cause` is intended to be optional, while the `error` of a `SuppressedError` must always be defined.
## Built-in Disposables
### `%IteratorPrototype%.@@dispose()`
We also propose to add `Symbol.dispose` to the built-in `%IteratorPrototype%` as if it had the following behavior:
```js%IteratorPrototype%[Symbol.dispose] = function () { this.return();}```
### `%AsyncIteratorPrototype%.@@asyncDispose()`
We propose to add `Symbol.asyncDispose` to the built-in `%AsyncIteratorPrototype%` as if it had the following behavior:
```js%AsyncIteratorPrototype%[Symbol.asyncDispose] = async function () { await this.return();}```
### Other Possibilities
We could also consider adding `Symbol.dispose` to such objects as the return value from `Proxy.revocable()`, but thatis currently out of scope for the current proposal.
## The Common `Disposable` and `AsyncDisposable` Interfaces
### The `Disposable` Interface
An object is _disposable_ if it conforms to the following interface:
| Property | Value | Requirements ||:-|:-|:-|| `@@dispose` | A function that performs explicit cleanup. | The function should return `undefined`. |
**TypeScript Definition**```tsinterface Disposable { /** * Disposes of resources within this object. */ [Symbol.dispose](): void;}```
### The `AsyncDisposable` Interface
An object is _async disposable_ if it conforms to the following interface:
| Property | Value | Requirements ||:-|:-|:-|| `@@asyncDispose` | An async function that performs explicit cleanup. | The function should return a `Promise`. |
**TypeScript Definition**```tsinterface AsyncDisposable { /** * Disposes of resources within this object. */ [Symbol.asyncDispose](): Promise<void>;}```
## The `DisposableStack` and `AsyncDisposableStack` container objects
This proposal adds two global objects that can act as containers to aggregate disposables, guaranteeing that everydisposable resource in the container is disposed when the respective disposal method is called. If any disposable in thecontainer throws an error during dispose, it would be thrown at the end (possibly wrapped in a `SuppressedError` ifmultiple errors were thrown):
```jsclass DisposableStack { constructor();
/** * Gets a value indicating whether the stack has been disposed. * @returns {boolean} */ get disposed();
/** * Alias for `[Symbol.dispose]()`. */ dispose();
/** * Adds a resource to the top of the stack. Has no effect if provided `null` or `undefined`. * @template {Disposable | null | undefined} T * @param {T} value - A `Disposable` object, `null`, or `undefined`. * @returns {T} The provided value. */ use(value);
/** * Adds a non-disposable resource and a disposal callback to the top of the stack. * @template T * @param {T} value - A resource to be disposed. * @param {(value: T) => void} onDispose - A callback invoked to dispose the provided value. * @returns {T} The provided value. */ adopt(value, onDispose);
/** * Adds a disposal callback to the top of the stack. * @param {() => void} onDispose - A callback to evaluate when this object is disposed. * @returns {void} */ defer(onDispose);
/** * Moves all resources currently in this stack into a new `DisposableStack`. * @returns {DisposableStack} The new `DisposableStack`. */ move();
/** * Disposes of resources within this object. * @returns {void} */ [Symbol.dispose]();
[Symbol.toStringTag];}```
`AsyncDisposableStack` is the async version of `DisposableStack` and is a container used to aggregate async disposables,guaranteeing that every disposable resource in the container is disposed when the respective disposal method is called.If any disposable in the container throws an error during dispose, or results in a rejected `Promise`, it would bethrown at the end (possibly wrapped in a `SuppressedError` if multiple errors were thrown):
These classes provided the following capabilities:- Aggregation- Interoperation and customization- Assist in complex construction
> **NOTE:** `DisposableStack` is inspired by Python's> [`ExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.ExitStack).
> **NOTE:** `AsyncDisposableStack` is inspired by Python's> [`AsyncExitStack`](https://docs.python.org/3/library/contextlib.html#contextlib.AsyncExitStack).
### Aggregation
The `DisposableStack` and `AsyncDisposableStack` classes provid the ability to aggregate multiple disposable resourcesinto a single container. When the `DisposableStack` container is disposed, each object in the container is alsoguaranteed to be disposed (barring early termination of the program). If any resource throws an error during dispose,it will be collected and rethrown after all resources are disposed. If there were multiple errors, they will be wrappedin nested `SuppressedError` objects.
For example:
```js// syncconst stack = new DisposableStack();const resource1 = stack.use(getResource1());const resource2 = stack.use(getResource2());const resource3 = stack.use(getResource3());stack[Symbol.dispose](); // disposes of resource3, then resource2, then resource1```
```js// asyncconst stack = new AsyncDisposableStack();const resource1 = stack.use(getResource1());const resource2 = stack.use(getResource2());const resource3 = stack.use(getResource3());await stack[Symbol.asyncDispose](); // dispose and await disposal result of resource3, then resource2, then resource1```
If all of `resource1`, `resource2` and `resource3` were to throw during disposal, this would produce an exceptionsimilar to the following:
```jsnew SuppressedError( /*error*/ exception_from_resource3_disposal, /*suppressed*/ new SuppressedError( /*error*/ exception_from_resource2_disposal, /*suppressed*/ exception_from_resource1_disposal ))```
### Interoperation and Customization
The `DisposableStack` and `AsyncDisposableStack` classes also provide the ability to create a disposable resource from asimple callback. This callback will be executed when the stack's disposal method is executed.
The ability to create a disposable resource from a callback has several benefits:
- It allows developers to leverage `using`/`await using` while working with existing resources that do not conform to the `Symbol.dispose`/`Symbol.asyncDispose` mechanic: ```js { using stack = new DisposableStack(); const reader = stack.adopt(createReader(), reader => reader.releaseLock()); ... } ```- It grants user the ability to schedule other cleanup work to evaluate at the end of the block similar to Go's `defer` statement: ```js function f() { using stack = new DisposableStack(); console.log("enter"); stack.defer(() => console.log("exit")); ... } ```
### Assist in Complex Construction
A user-defined disposable class might need to allocate and track multiple nested resources that should be disposed whenthe class instance is disposed. However, properly managing the lifetime of these nested resources in the classconstructor can sometimes be difficult. The `move` method of `DisposableStack`/`AsyncDisposableStack` helps to moreeasily manage lifetime in these scenarios:
```js// syncclass PluginHost { #disposed = false; #disposables; #channel; #socket;
constructor() { // Create a DisposableStack that is disposed when the constructor exits. // If construction succeeds, we move everything out of `stack` and into // `#disposables` to be disposed later. using stack = new DisposableStack();
// Create an IPC adapter around process.send/process.on("message"). // When disposed, it unsubscribes from process.on("message"). this.#channel = stack.use(new NodeProcessIpcChannelAdapter(process));
// Create a pseudo-websocket that sends and receives messages over // a NodeJS IPC channel. this.#socket = stack.use(new NodePluginHostIpcSocket(this.#channel));
// If we made it here, then there were no errors during construction and // we can safely move the disposables out of `stack` and into `#disposables`. this.#disposables = stack.move();
// If construction failed, then `stack` would be disposed before reaching // the line above. Event handlers would be removed, allowing `#channel` and // `#socket` to be GC'd. }
loadPlugin(file) { // A disposable should try to ensure access is consistent with its "disposed" state, though this isn't strictly // necessary since some disposables could be reusable (i.e., a Connection with an `open()` method, etc.). if (this.#disposed) throw new ReferenceError("Object is disposed."); // ... }
[Symbol.dispose]() { if (!this.#disposed) { this.#disposed = true; const disposables = this.#disposables;
// NOTE: we can free `#socket` and `#channel` here since they will be disposed by the call to // `disposables[Symbol.dispose]()`, below. This isn't strictly a requirement for every Disposable, but is // good housekeeping since these objects will no longer be useable. this.#socket = undefined; this.#channel = undefined; this.#disposables = undefined;
// Dispose all resources in `disposables` disposables[Symbol.dispose](); } }}```
```js// asyncconst privateConstructorSentinel = {};
class AsyncPluginHost { #disposed = false; #disposables; #channel; #socket;
/** @private */ constructor(arg) { if (arg !== privateConstructorSentinel) throw new TypeError("Use AsyncPluginHost.create() instead"); } // NOTE: there's no such thing as an async constructor static async create() { const host = new AsyncPluginHost(privateConstructorSentinel);
// Create an AsyncDisposableStack that is disposed when the constructor exits. // If construction succeeds, we move everything out of `stack` and into // `#disposables` to be disposed later. await using stack = new AsyncDisposableStack();
// Create an IPC adapter around process.send/process.on("message"). // When disposed, it unsubscribes from process.on("message"). host.#channel = stack.use(new NodeProcessIpcChannelAdapter(process));
// Create a pseudo-websocket that sends and receives messages over // a NodeJS IPC channel. host.#socket = stack.use(new NodePluginHostIpcSocket(host.#channel));
// If we made it here, then there were no errors during construction and // we can safely move the disposables out of `stack` and into `#disposables`. host.#disposables = stack.move();
// If construction failed, then `stack` would be asynchronously disposed before reaching // the line above. Event handlers would be removed, allowing `#channel` and // `#socket` to be GC'd. return host; }
loadPlugin(file) { // A disposable should try to ensure access is consistent with its "disposed" state, though this isn't strictly // necessary since some disposables could be reusable (i.e., a Connection with an `open()` method, etc.). if (this.#disposed) throw new ReferenceError("Object is disposed."); // ... }
async [Symbol.asyncDispose]() { if (!this.#disposed) { this.#disposed = true; const disposables = this.#disposables;
// NOTE: we can free `#socket` and `#channel` here since they will be disposed by the call to // `disposables[Symbol.asyncDispose]()`, below. This isn't strictly a requirement for every disposable, but is // good housekeeping since these objects will no longer be useable. this.#socket = undefined; this.#channel = undefined; this.#disposables = undefined;
// Dispose all resources in `disposables` await disposables[Symbol.asyncDispose](); } }}```
### Subclassing `Disposable` Classes
You can also use a `DisposableStack` to assist with disposal in a subclass constructor whose superclass is disposable:
```jsclass DerivedPluginHost extends PluginHost { constructor() { super();
// Create a DisposableStack to cover the subclass constructor. using stack = new DisposableStack();
// Defer a callback to dispose resources on the superclass. We use `defer` so that we can invoke the version of // `[Symbol.dispose]` on the superclass and not on this or any subclasses. stack.defer(() => super[Symbol.dispose]());
// If any operations throw during subclass construction, the instance will still be disposed, and superclass // resources will be freed doSomethingThatCouldPotentiallyThrow();
// As the last step before exiting, empty out the DisposableStack so that we don't dispose ourselves. stack.move(); }}```
Here, we can use `stack` to track the result of `super()` (i.e., the `this` value). If any exception occurs duringsubclass construction, we can ensure that `[Symbol.dispose]()` is called, freeing resources. If the subclass also needsto track its own disposable resources, this example is modified slightly:
```jsclass DerivedPluginHostWithOwnDisposables extends PluginHost { #logger; #disposables;
constructor() { super()
// Create a DisposableStack to cover the subclass constructor. using stack = new DisposableStack();
// Defer a callback to dispose resources on the superclass. We use `defer` so that we can invoke the version of // `[Symbol.dispose]` on the superclass and not on this or any subclasses. stack.defer(() => super[Symbol.dispose]());
// Create a logger that uses the file system and add it to our own disposables. this.#logger = stack.use(new FileLogger());
// If any operations throw during subclass construction, the instance will still be disposed, and superclass // resources will be freed doSomethingThatCouldPotentiallyThrow();
// Persist our own disposables. If construction fails prior to the call to `stack.move()`, our own disposables // will be disposed before they are set, and then the superclass `[Symbol.dispose]` will be invoked. this.#disposables = stack.move(); }
[Symbol.dispose]() { this.#logger = undefined;
// Dispose of our resources and those of our superclass. We do not need to invoke `super[Symbol.dispose]()` since // that is already tracked by the `stack.defer` call in the constructor. this.#disposables[Symbol.dispose](); }}```
In this example, we can simply add new resources to the `stack` and move its contents into the subclass instance's`this.#disposables`. In the subclass `[Symbol.dispose]()` method we don't need to call `super[Symbol.dispose]()` sincethat has already been tracked by the `stack.defer` call in the constructor.
# Relation to `Iterator` and `for..of`
Iterators in ECMAScript also employ a "cleanup" step by way of supplying a `return` method. This means that there issome similarity between a `using` declaration and a `for..of` statement:
```js// usingfunction f() { using x = ...; // use x} // x is disposed
// for..offunction makeDisposableScope() { const resources = []; let state = 0; return { next() { switch (state) { case 0: state++; return { done: false, value: { use(value) { resources.unshift(value); return value; } } }; case 1: state++; for (const value of resources) { value?.[Symbol.dispose](); } default: state = -1; return { done: true }; } }, return() { switch (state) { case 1: state++; for (const value of resources) { value?.[Symbol.dispose](); } default: state = -1; return { done: true }; } }, [Symbol.iterator]() { return this; } }}
function f() { for (const { use } of makeDisposableScope()) { const x = use(...); // use x } // x is disposed}```
However there are a number drawbacks to using `for..of` as an alternative:
- Exceptions in the body are swallowed by exceptions from disposables.- `for..of` implies iteration, which can be confusing when reading code.- Conflating `for..of` and resource management could make it harder to find documentation, examples, StackOverflow answers, etc.- A `for..of` implementation like the one above cannot control the scope of `use`, which can make lifetimes confusing: ```js for (const { use } of ...) { const x = use(...); // ok setImmediate(() => { const y = use(...); // wrong lifetime }); } ```- Significantly more boilerplate compared to `using`.- Mandates introduction of a new block scope, even at the top level of a function body.- Control flow analysis of a `for..of` loop cannot infer definite assignment since a loop could potentially have zero elements: ```js // using function f1() { /** @type {string | undefined} */ let x; { using y = ...; x = y.text; } x.toString(); // x is definitely assigned }
// for..of function f2() { /** @type {string | undefined} */ let x; for (const { use } of ...) { const y = use(...); x = y.text; } x.toString(); // possibly an error in a static analyzer since `x` is not guaranteed to have been assigned. } ```- Using `continue` and `break` is more difficult if you need to dispose of an iterated value: ```js // using for (using x of iterable) { if (!x.ready) continue; if (x.done) break; ... }
// for..of outer: for (const x of iterable) { for (const { use } of ...) { use(x); if (!x.ready) continue outer; if (!x.done) break outer; ... } } ```
# Relation to DOM APIs
This proposal does not necessarily require immediate support in the HTML DOM specification, as existing APIs can stillbe adapted by using `DisposableStack` or `AsyncDisposableStack`. However, there are a number of APIs that could benefitfrom this proposal and should be considered by the relevant standards bodies. The following is by no means a completelist, and primarily offers suggestions for consideration. The actual implementation is at the discretion of the relevantstandards bodies.
- `AudioContext` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`. - NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.- `BroadcastChannel` — `@@dispose()` as an alias or [wrapper][] for `close()`.- `EventSource` — `@@dispose()` as an alias or [wrapper][] for `close()`.- `FileReader` — `@@dispose()` as an alias or [wrapper][] for `abort()`.- `IDbTransaction` — `@@dispose()` could invoke `abort()` if the transaction is still in the active state: ```js { using tx = db.transaction(storeNames); // ... if (...) throw new Error(); // ... tx.commit(); } // implicit tx.abort() if we don't reach the explicit tx.commit() ```- `ImageBitmap` — `@@dispose()` as an alias or [wrapper][] for `close()`.- `IntersectionObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.- `MediaKeySession` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`. - NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.- `MessagePort` — `@@dispose()` as an alias or [wrapper][] for `close()`.- `MutationObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.- `PaymentRequest` — `@@asyncDispose()` could invoke `abort()` if the payment is still in the active state. - NOTE: `abort()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.- `PerformanceObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.- `PushSubscription` — `@@asyncDispose()` as an alias or [wrapper][] for `unsubscribe()`.- `ReadableStream` — `@@asyncDispose()` as an alias or [wrapper][] for `cancel()`.- `ReadableStreamDefaultReader` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or `@@asyncDispose()` as a [wrapper][] for `cancel()` (but probably not both).- `RTCPeerConnection` — `@@dispose()` as an alias or [wrapper][] for `close()`.- `RTCRtpTransceiver` — `@@dispose()` as an alias or [wrapper][] for `stop()`.- `ReadableStreamDefaultController` — `@@dispose()` as an alias or [wrapper][] for `close()`.- `ReadableStreamDefaultReader` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or- `ResizeObserver` — `@@dispose()` as an alias or [wrapper][] for `disconnect()`.- `ServiceWorkerRegistration` — `@@asyncDispose()` as a [wrapper][] for `unregister()`.- `SourceBuffer` — `@@dispose()` as a [wrapper][] for `abort()`.- `TransformStreamDefaultController` — `@@dispose()` as an alias or [wrapper][] for `terminate()`.- `WebSocket` — `@@dispose()` as a [wrapper][] for `close()`.- `Worker` — `@@dispose()` as an alias or [wrapper][] for `terminate()`.- `WritableStream` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`. - NOTE: `close()` here is asynchronous, but uses the same name as similar synchronous methods on other objects.- `WritableStreamDefaultWriter` — Either `@@dispose()` as an alias or [wrapper][] for `releaseLock()`, or `@@asyncDispose()` as a [wrapper][] for `close()` (but probably not both).- `XMLHttpRequest` — `@@dispose()` as an alias or [wrapper][] for `abort()`.
In addition, several new APIs could be considered that leverage this functionality:
- `EventTarget.prototype.addEventListener(type, listener, { subscription: true }) -> Disposable` — An option passed to `addEventListener` could return a `Disposable` that removes the event listener when disposed.- `Performance.prototype.measureBlock(measureName, options) -> Disposable` — Combines `mark` and `measure` into a block-scoped disposable: ```js function f() { using measure = performance.measureBlock("f"); // marks on entry // ... } // marks and measures on exit ```- `SVGSVGElement` — A new method producing a [single-use disposer][] for `pauseAnimations()` and `unpauseAnimations()`.- `ScreenOrientation` — A new method producing a [single-use disposer][] for `lock()` and `unlock()`.
### Definitions
A _wrapper for `x()`_ is a method that invokes `x()`, but only if the object is in a statesuch that calling `x()` will not throw as a result of repeated evaluation.
A _callback-adapting wrapper_ is a _wrapper_ that adapts a continuation passing-style methodthat accepts a callback into a `Promise`-producing method.
A _single-use disposer for `x()` and `y()`_ indicates a newly constructed disposable objectthat invokes `x()` when constructed and `y()` when disposed the first time (and does nothing if the object is disposedmore than once).
# Relation to NodeJS APIs
This proposal does not necessarily require immediate support in NodeJS, as existing APIs can still be adapted by using`DisposableStack` or `AsyncDisposableStack`. However, there are a number of APIs that could benefit from this proposaland should be considered by the NodeJS maintainers. The following is by no means a complete list, and primarily offerssuggestions for consideration. The actual implementation is at the discretion of the NodeJS maintainers.
- Anything with `ref()` and `unref()` methods — A new method or API that produces a [single-use disposer][] for `ref()` and `unref()`.- Anything with `cork()` and `uncork()` methods — A new method or API that produces a [single-use disposer][] for `cork()` and `uncork()`.- `async_hooks.AsyncHook` — either `@@dispose()` as an alias or [wrapper][] for `disable()`, or a new method that produces a [single-use disposer][] for `enable()` and `disable()`.- `child_process.ChildProcess` — `@@dispose()` as an alias or [wrapper][] for `kill()`.- `cluster.Worker` — `@@dispose()` as an alias or [wrapper][] for `kill()`.- `crypto.Cipher`, `crypto.Decipher` — `@@dispose()` as a [wrapper][] for `final()`.- `crypto.Hash`, `crypto.Hmac` — `@@dispose()` as a [wrapper][] for `digest()`.- `dns.Resolver`, `dnsPromises.Resolver` — `@@dispose()` as an alias or [wrapper][] for `cancel()`.- `domain.Domain` — A new method or API that produces a [single-use disposer][] for `enter()` and `exit()`.- `events.EventEmitter` — A new method or API that produces a [single-use disposer][] for `on()` and `off()`.- `fs.promises.FileHandle` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`.- `fs.Dir` — `@@asyncDispose()` as an alias or [wrapper][] for `close()`, `@@dispose()` as an alias or [wrapper][] for `closeSync()`.- `fs.FSWatcher` — `@@dispose()` as an alias or [wrapper][] for `close()`.- `http.Agent` — `@@dispose()` as an alias or [wrapper][] for `destroy()`.- `http.ClientRequest` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.- `http.Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.- `http.ServerResponse` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `end()`.- `http.IncomingMessage` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.- `http.OutgoingMessage` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.- `http2.Http2Session` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.- `http2.Http2Stream` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.- `http2.Http2Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.- `http2.Http2SecureServer` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.- `http2.Http2ServerRequest` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.- `http2.Http2ServerResponse` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `end()`.- `https.Server` — `@@asyncDispose()` as a [callback-adapting wrapper][] for `close()`.- `inspector` — A new API that produces a [single-use disposer][] for `open()` and `close()`.- `stream.Writable` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()` or `@@asyncDispose` only as a [callback-adapting wrapper][] for `end()` (depending on whether the disposal behavior should be to drop immediately or to flush any pending writes).- `stream.Readable` — Either `@@dispose()` or `@@asyncDispose()` as an alias or [wrapper][] for `destroy()`.- ... and many others in `net`, `readline`, `tls`, `udp`, and `worker_threads`.
## Linked Issue #1 — Async using syntax
I've seen different syntax suggestions related to async disposal spread over different issues, in particular tc39/proposal-explicit-resource-management#16 tc39/proposal-explicit-resource-management#76 tc39/proposal-explicit-resource-management#84 tc39/proposal-async-explicit-resource-management#4. I wanted to concentrate the discussion in a single issue.
I'd first like to discuss the ongoing assumption that `using` an async-disposable requires specific syntax.The way I model the `using` syntax is that a block containing a `using` declaration implicitly creates a `DisposableStack`. Every `using` declaration implicitly results in a `.use()` on the stack, and that exiting the block implicitly calls `[Symbol.dispose]()` on the stack.
Now if we assume that we have a concept of "async blocks", instead of a `DisposableStack` being implicitly created, it'd be an `AsyncDisposableStack`. At that point any `using` declaration would similarly call the `.use()` of the implicit async disposable stack, which is a synchronous operation, and it's the exit of the "async block" which awaits the `[Symbol.asyncDispose]()` call.
As such I would be against any syntax that uses the `await` keyword for the `using` declaration, as nothing is awaited at the declaration time. Similarly I would be against any syntax that doesn't use the `await` keyword on the block as a marker of interleaving. I would be ok with a `async using` declaration to be explicit, but I would consider that unnecessary verbosity.
Given the mental model above, I believe it would be entirely natural that `for await (using r of ...)`, and `using` declarations inside `for-await-of` blocks in general, would implicitly use an `AsyncDisposableStack`. `for-await-of` is conceptually the only "async block" in the language at the moment. Then it become a matter of specifying what the syntax of an "async block" not tied to iteration looks like.
*Source: https://github.com/tc39/proposal-async-explicit-resource-management/issues/1*1234567#!/usr/bin/env bashset -euo pipefail
cd /workspace/typescriptpatch=${LOLBENCH_ORACLE_PATCH:-/solution/solution.patch}git apply "$patch"lolbench-submit123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960schema_version = "1.3"
[task]name = "lolbench/TypeScript_2"description = "Implement TypeScript using and await using declarations."authors = [{ name = "LoLBench maintainers" }]keywords = ["lolbench", "coding-agent", "typescript"]
[metadata]instance_id = "TypeScript_2"source_instance_id = "TypeScript_PR-54505_Using-and-await-using-declarations"source_slug = "TypeScript_PR-54505_Using-and-await-using-declarations"docker_slug = "TypeScript_PR-54505_Using-and-await-using-declarations"dockerhub_image = "smartdub26/lolbench-linux:TypeScript_2-1.0.0"project = "TypeScript"repo = "microsoft/TypeScript"requirement_doc = "https://github.com/tc39/proposal-explicit-resource-management"pr_link = "https://github.com/microsoft/TypeScript/pull/54505"base_commit = "d90eb0d731c3f74b131dcfafe69ef5341ed14934"merge_commit = "558a5028b785e962e7a26a9d820fc77ca094faf6"test_level = "system"source_history_policy = "ancestors-only"lolbench_test_modes = ["orig", "aug", "union"]default_lolbench_suite = "union"canonical_lolbench_suite = "union"augmentation_available = trueverifier_network_policy = "public"verifier_network_reason = "The Harbor verifier runs in a separate container and may use network access; migrated LoLBench verifier assets are mounted only in the verifier phase."
[environment]build_timeout_sec = 3600.0docker_image = "smartdub26/lolbench-linux:TypeScript_2-1.0.0"network_mode = "public"os = "linux"cpus = 4memory_mb = 7168storage_mb = 20480
[agent]timeout_sec = 21600.0user = "agent"network_mode = "allowlist"allowed_hosts = ["openrouter.ai", "api.openai.com", "api.anthropic.com"]
[verifier]timeout_sec = 7200.0user = "root"environment_mode = "separate"network_mode = "public"
[verifier.env]LOLBENCH_SUITE = "union"
[verifier.environment]docker_image = "smartdub26/lolbench-linux:TypeScript_2-1.0.0"network_mode = "public"os = "linux"cpus = 4memory_mb = 7168storage_mb = 2048012345678910111213141516services: main: pull_policy: missing volumes: - type: bind source: . target: /tests read_only: true - type: bind source: ./private target: /opt/lolbench/private read_only: true - type: bind source: ../solution target: /solution read_only: true123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255diff --git a/tests/cases/fourslash/usingAugDiagnosticsAndLib.ts b/tests/cases/fourslash/usingAugDiagnosticsAndLib.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/usingAugDiagnosticsAndLib.ts@@ -0,0 +1,97 @@+/// <reference path="fourslash.ts" />++////const placeholder = 0;++function diagnostics(source: string): string[] {+ const fileName = "/usingAug.ts";+ const compilerOptions: ts.CompilerOptions = {+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.ESNext,+ lib: ["lib.esnext.d.ts"],+ strict: true,+ types: [],+ };+ const host = ts.createCompilerHost(compilerOptions);+ const readFile = host.readFile.bind(host);+ const fileExists = host.fileExists.bind(host);++ host.readFile = file => file === fileName ? source : readFile(file);+ host.fileExists = file => file === fileName || fileExists(file);+ host.getSourceFile = (file, languageVersion) => {+ const text = file === fileName ? source : readFile(file);+ return text === undefined ? undefined : ts.createSourceFile(file, text, languageVersion, /*setParentNodes*/ true);+ };++ const program = ts.createProgram([fileName], compilerOptions, host);+ return ts.getPreEmitDiagnostics(program).map(diagnostic =>+ ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n")+ );+}++function assertHasDiagnostic(actual: string[], expected: string) {+ assert.ok(+ actual.some(message => message.includes(expected)),+ `Expected diagnostic containing ${JSON.stringify(expected)}, got:\n${actual.join("\n")}`+ );+}++function assertNoDiagnostics(actual: string[]) {+ assert.deepStrictEqual(actual, []);+}++assertHasDiagnostic(+ diagnostics("function f() { using resource = {}; }"),+ "[Symbol.dispose]",+);++assertHasDiagnostic(+ diagnostics("async function f() { await using resource = {}; }"),+ "[Symbol.asyncDispose]",+);++assertNoDiagnostics(diagnostics(`+function syncNullish() {+ using nullResource = null;+ using undefinedResource = undefined;+}++async function asyncNullish() {+ await using nullResource = null;+ await using undefinedResource = undefined;+}+`));++assertNoDiagnostics(diagnostics(`+class Resource implements AsyncDisposable {+ [Symbol.asyncDispose](): Promise<void> {+ return Promise.resolve();+ }+}++async function f() {+ await using resource = new Resource();+}+`));++assertNoDiagnostics(diagnostics(`+declare const resource: AsyncDisposable;+const cleanup: PromiseLike<void> = resource[Symbol.asyncDispose]();+cleanup.then(() => undefined);+`));++assertNoDiagnostics(diagnostics(`+let disposeSymbol: typeof Symbol.dispose;+let asyncDisposeSymbol: typeof Symbol.asyncDispose;+let disposable: Disposable;+let asyncDisposable: AsyncDisposable;+`));++assertHasDiagnostic(+ diagnostics("function f() { using resource = { [Symbol.dispose]() {} }; resource = { [Symbol.dispose]() {} }; }"),+ "Cannot assign to 'resource' because it is a constant.",+);++assertHasDiagnostic(+ diagnostics("function f() { { using scoped = { [Symbol.dispose]() {} }; } scoped; }"),+ "Cannot find name 'scoped'.",+);diff --git a/tests/cases/fourslash/usingAugEmitHelpers.ts b/tests/cases/fourslash/usingAugEmitHelpers.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/usingAugEmitHelpers.ts@@ -0,0 +1,106 @@+/// <reference path="fourslash.ts" />++////const placeholder = 0;++function emit(source: string): string {+ return ts.transpileModule(source, {+ compilerOptions: {+ target: ts.ScriptTarget.ES2018,+ module: ts.ModuleKind.CommonJS,+ },+ }).outputText;+}++function assertIncludes(text: string, expected: string) {+ assert.ok(+ text.includes(expected),+ `Expected emitted text to include ${JSON.stringify(expected)}.\nActual:\n${text}`+ );+}++function assertMatches(text: string, expected: RegExp) {+ assert.ok(+ expected.test(text),+ `Expected emitted text to match ${expected}.\nActual:\n${text}`+ );+}++function runCommonJs(outputText: string) {+ const symbols = Symbol as any;+ symbols.dispose ||= Symbol("dispose");+ symbols.asyncDispose ||= Symbol("asyncDispose");+ const sandbox: { result?: unknown } = {};+ new Function("Symbol", "globalThis", outputText)(symbols, sandbox);+ return sandbox.result;+}++const syncOutput = emit(`+function run() {+ const events: string[] = [];+ {+ using first = { [Symbol.dispose]() { events.push("first"); } };+ using second = { [Symbol.dispose]() { events.push("second"); } };+ events.push("body");+ }+ return events.join(",");+}+globalThis.result = run();+`);++assertMatches(syncOutput, /__addDisposableResource\(env_\d+, \{ \[Symbol\.dispose\]\(\) \{ events\.push\("first"\); \} \}, false\)/);+assertMatches(syncOutput, /new SuppressedError\([^)]*"An error was suppressed during disposal\."\)/);+assert.strictEqual(runCommonJs(syncOutput), "body,second,first");++const suppressedOutput = emit(`+function run() {+ try {+ using resource = { [Symbol.dispose]() { throw "dispose"; } };+ throw "body";+ }+ catch (error) {+ return [error.name, error.error, error.suppressed].join(",");+ }+}+globalThis.result = run();+`);++assert.strictEqual(runCommonJs(suppressedOutput), "SuppressedError,dispose,body");++const asyncOutput = emit(`+async function run() {+ const events: string[] = [];+ {+ await using empty = null;+ await using syncFallback = { [Symbol.dispose]() { events.push("sync"); } };+ await using asyncResource = { async [Symbol.asyncDispose]() { events.push("async"); } };+ }+ return events.join(",");+}+`);++assertIncludes(asyncOutput, "__addDisposableResource(env_1, null, true)");+assertMatches(asyncOutput, /__addDisposableResource\(env_\d+, \{ \[Symbol\.dispose\]\(\) \{ events\.push\("sync"\); \} \}, true\)/);+assertMatches(asyncOutput, /__addDisposableResource\(env_\d+, \{ async \[Symbol\.asyncDispose\]\(\) \{ events\.push\("async"\); \} \}, true\)/);+assertIncludes(asyncOutput, "dispose = value[Symbol.dispose];");+assertIncludes(asyncOutput, "Promise.resolve(result).then(next");+assertMatches(asyncOutput, /if \(result_\d+\)\s+await result_\d+;/);++const parsed = ts.createSourceFile(+ "usingFlags.ts",+ "function f() { using sync = null; } async function g() { await using asyncResource = null; }",+ ts.ScriptTarget.Latest,+ /*setParentNodes*/ true,+ ts.ScriptKind.TS,+);+const syncStatement = ((parsed.statements[0] as ts.FunctionDeclaration).body!.statements[0] as ts.VariableStatement);+const asyncStatement = ((parsed.statements[1] as ts.FunctionDeclaration).body!.statements[0] as ts.VariableStatement);++assert.strictEqual(+ syncStatement.declarationList.flags & ts.NodeFlags.BlockScoped,+ ts.NodeFlags.Using,+);+assert.strictEqual(+ asyncStatement.declarationList.flags & ts.NodeFlags.BlockScoped,+ ts.NodeFlags.AwaitUsing,+);+assert.ok((syncStatement.declarationList.flags & ts.NodeFlags.Constant) !== 0);diff --git a/tests/cases/fourslash/usingAugVariableDeclarationP2P.ts b/tests/cases/fourslash/usingAugVariableDeclarationP2P.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/usingAugVariableDeclarationP2P.ts@@ -0,0 +1,14 @@+/// <reference path="fourslash.ts" />++////function ordinaryVariableFlow(flag: boolean) {+//// let outer = 1;+//// if (flag) {+//// const /*inner*/inner = "nested";+//// inner.toUpperCase();+//// }+//// outer = outer + 1;+//// return outer;+////}++verify.quickInfoAt("inner", "const inner: \"nested\"");+verify.noErrors();diff --git a/tests/cases/fourslash/usingAugForOfP2P.ts b/tests/cases/fourslash/usingAugForOfP2P.tsnew file mode 100644index 0000000000..1111111111--- /dev/null+++ b/tests/cases/fourslash/usingAugForOfP2P.ts@@ -0,0 +1,14 @@+/// <reference path="fourslash.ts" />++////const numbers = [1, 2, 3];+////for (const /*item*/item of numbers) {+//// item.toFixed();+////}+////const words = ["a", "b"];+////for (const /*text*/text of words) {+//// text.toUpperCase();+////}++verify.quickInfoAt("item", "const item: number");+verify.quickInfoAt("text", "const text: string");+verify.noErrors();12345678910111213141516tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.tstests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.tstests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts12tests/cases/fourslash/usingAugDiagnosticsAndLib.tstests/cases/fourslash/usingAugEmitHelpers.ts1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInitializer.tstests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.tstests/cases/conformance/statements/VariableStatements/everyTypeWithInitializer.tstests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.tstests/cases/conformance/statements/VariableStatements/recursiveInitializer.tstests/cases/conformance/statements/VariableStatements/validMultipleVariableDeclarations.tstests/cases/conformance/es6/for-ofStatements/for-of1.tstests/cases/conformance/es6/for-ofStatements/for-of10.tstests/cases/conformance/es6/for-ofStatements/for-of11.tstests/cases/conformance/es6/for-ofStatements/for-of12.tstests/cases/conformance/es6/for-ofStatements/for-of13.tstests/cases/conformance/es6/for-ofStatements/for-of14.tstests/cases/conformance/es6/for-ofStatements/for-of15.tstests/cases/conformance/es6/for-ofStatements/for-of16.tstests/cases/conformance/es6/for-ofStatements/for-of17.tstests/cases/conformance/es6/for-ofStatements/for-of18.tstests/cases/conformance/es6/for-ofStatements/for-of19.tstests/cases/conformance/es6/for-ofStatements/for-of2.tstests/cases/conformance/es6/for-ofStatements/for-of20.tstests/cases/conformance/es6/for-ofStatements/for-of21.tstests/cases/conformance/es6/for-ofStatements/for-of22.tstests/cases/conformance/es6/for-ofStatements/for-of23.tstests/cases/conformance/es6/for-ofStatements/for-of24.tstests/cases/conformance/es6/for-ofStatements/for-of25.tstests/cases/conformance/es6/for-ofStatements/for-of26.tstests/cases/conformance/es6/for-ofStatements/for-of27.tstests/cases/conformance/es6/for-ofStatements/for-of28.tstests/cases/conformance/es6/for-ofStatements/for-of3.tstests/cases/conformance/es6/for-ofStatements/for-of4.tstests/cases/conformance/es6/for-ofStatements/for-of5.tstests/cases/conformance/es6/for-ofStatements/for-of6.tstests/cases/conformance/es6/for-ofStatements/for-of7.tstests/cases/conformance/es6/for-ofStatements/for-of8.tstests/cases/conformance/es6/for-ofStatements/for-of9.tstests/cases/conformance/es6/for-ofStatements/for-of29.tstests/cases/conformance/es6/for-ofStatements/for-of30.tstests/cases/conformance/es6/for-ofStatements/for-of31.tstests/cases/conformance/es6/for-ofStatements/for-of32.tstests/cases/conformance/es6/for-ofStatements/for-of33.tstests/cases/conformance/es6/for-ofStatements/for-of34.tstests/cases/conformance/es6/for-ofStatements/for-of35.tstests/cases/conformance/es6/for-ofStatements/for-of36.tstests/cases/conformance/es6/for-ofStatements/for-of37.tstests/cases/conformance/es6/for-ofStatements/for-of38.tstests/cases/conformance/es6/for-ofStatements/for-of39.tstests/cases/conformance/es6/for-ofStatements/for-of40.tstests/cases/conformance/es6/for-ofStatements/for-of41.tstests/cases/conformance/es6/for-ofStatements/for-of42.tstests/cases/conformance/es6/for-ofStatements/for-of43.tstests/cases/conformance/es6/for-ofStatements/for-of44.ts12tests/cases/fourslash/usingAugVariableDeclarationP2P.tstests/cases/fourslash/usingAugForOfP2P.ts123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337#!/usr/bin/env bash# LoLBench runner for microsoft/TypeScript PR-54505 (using / await using declarations).## Eval contract:# docker run --rm --network=none \# -v $(pwd)/solution.patch:/in/solution.patch:ro \# -v $(pwd)/out:/out \# lolbench/apache-ts-pr-54505:1# → /out/agent_report.json (sanitized).## Validation modes:# LOLBENCH_MODE=validate_pre # F2P FAIL (parser doesn't know `using` declarations), P2P PASS# LOLBENCH_MODE=validate_post # all PASS
set -uo pipefailPRIV=/opt/lolbench/privateWS=/workspaceTS=$WS/typescriptMODE=${LOLBENCH_MODE:-eval}SUITE=${LOLBENCH_SUITE:-orig}
case "$SUITE" in orig|aug|union) ;; *) echo "[run_tests $MODE] FATAL: unknown LOLBENCH_SUITE=$SUITE" >&2; exit 2 ;;esac
HAS_AUG=0if [ -f "$PRIV/eval_tests_aug.patch" ] \ && [ -f "$PRIV/f2p_aug.txt" ] \ && [ -f "$PRIV/p2p_aug.txt" ]; then HAS_AUG=1fiif [ "$SUITE" != "orig" ] && [ "$HAS_AUG" -eq 0 ]; then echo "[run_tests $MODE/$SUITE] WARN: no augmented sidecar shipped; falling back to orig" >&2 SUITE=origfi
log() { echo "[run_tests $MODE/$SUITE] $*" >&2; }die() { log "FATAL: $*"; emit_error harness_error false skipped; exit 0; }
FAIL_TO_PASS=()PASS_TO_PASS=()
emit_error() { local cat=$1 applied=$2 build_status=$3 local f2p_n=${#FAIL_TO_PASS[@]} local p2p_n=${#PASS_TO_PASS[@]} python3 - "$cat" "$applied" "$build_status" "$f2p_n" "$p2p_n" "$SUITE" "$HAS_AUG" <<'EOF' >/out/agent_report.jsonimport json, syscat, applied_s, build_s, f2p_n, p2p_n, suite, has_aug_s = sys.argv[1:8]applied = applied_s.lower() == "true"print(json.dumps({ "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", "suite": suite, "augmentation_available": has_aug_s == "1", "applied": applied, "build": {"status": build_s}, "f2p": {"passed":0,"failed":0,"errored":int(f2p_n),"skipped":0,"total":int(f2p_n)}, "p2p": {"passed":0,"failed":0,"errored":int(p2p_n),"skipped":0,"total":int(p2p_n)}, "resolved": False, "error_categories": [cat]}, indent=2))EOF}
mapfile -t FAIL_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/f2p.txt")mapfile -t PASS_TO_PASS_ORIG < <(grep -v '^\s*$' "$PRIV/p2p.txt")FAIL_TO_PASS_AUG=()PASS_TO_PASS_AUG=()if [ "$HAS_AUG" -eq 1 ]; then mapfile -t FAIL_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/f2p_aug.txt") mapfile -t PASS_TO_PASS_AUG < <(grep -v '^\s*$' "$PRIV/p2p_aug.txt")fi
case "$SUITE" in orig) FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}") PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}") ;; aug) FAIL_TO_PASS=("${FAIL_TO_PASS_AUG[@]}") PASS_TO_PASS=("${PASS_TO_PASS_AUG[@]}") ;; union) FAIL_TO_PASS=("${FAIL_TO_PASS_ORIG[@]}" "${FAIL_TO_PASS_AUG[@]}") PASS_TO_PASS=("${PASS_TO_PASS_ORIG[@]}" "${PASS_TO_PASS_AUG[@]}") ;;esac
F2P_EFFECTIVE=$WS/.f2p_effective.txtP2P_EFFECTIVE=$WS/.p2p_effective.txtprintf '%s\n' "${FAIL_TO_PASS[@]}" >"$F2P_EFFECTIVE"printf '%s\n' "${PASS_TO_PASS[@]}" >"$P2P_EFFECTIVE"
# Sanity-check spec ↔ selectors agreepython3 - "$PRIV/spec.json" "$PRIV/f2p.txt" "$PRIV/p2p.txt" "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$SUITE" <<'EOF' || die "spec/selector mismatch"import json, sysspec = json.load(open(sys.argv[1]))orig_f2p = [l.strip() for l in open(sys.argv[2]) if l.strip()]orig_p2p = [l.strip() for l in open(sys.argv[3]) if l.strip()]eff_f2p = [l.strip() for l in open(sys.argv[4]) if l.strip()]eff_p2p = [l.strip() for l in open(sys.argv[5]) if l.strip()]suite = sys.argv[6]aug = spec.get("augmented", {})expected = { "orig": (spec["fail_to_pass"], spec["pass_to_pass"]), "aug": (aug.get("fail_to_pass", []), aug.get("pass_to_pass", [])), "union": (orig_f2p + aug.get("fail_to_pass", []), orig_p2p + aug.get("pass_to_pass", [])),}[suite]sys.exit(0 if expected == (eff_f2p, eff_p2p) else 1)EOF
# ---- pick source-side patch by mode ---------------------------------SRC_PATCH=""case "$MODE" in validate_pre) SRC_PATCH="" ;; validate_post) if [ -f /solution/solution.patch ]; then SRC_PATCH=/solution/solution.patch else SRC_PATCH="$PRIV/solution.patch" fi ;; eval) if [ ! -f /in/solution.patch ]; then log "no /in/solution.patch mounted" emit_error missing_solution_patch false skipped exit 0 fi AGENT_PATCH=/tmp/lolbench_agent_patch.diff cp /in/solution.patch "$AGENT_PATCH" chmod 0600 "$AGENT_PATCH" SRC_PATCH="$AGENT_PATCH" ;; *) die "unknown LOLBENCH_MODE=$MODE" ;;esac
# ---- reset workspace + apply patches --------------------------------cd "$TS"git config --global --add safe.directory "$TS"git reset --hard >/dev/null 2>&1git clean -fdx -e node_modules -e built >/dev/null 2>&1
if [ -n "$SRC_PATCH" ]; then if ! git apply --check "$SRC_PATCH" 2>/tmp/apply.err; then log "source patch did not apply cleanly:"; cat /tmp/apply.err >&2 emit_error patch_apply_failure false skipped; exit 0 fi git apply "$SRC_PATCH" # LoLBench eval-patch-collision guard (re-verify remediation): if the agent patch touched files the # eval test patches own (test fixtures the agent must not modify), restore # those paths (both sides of every diff/rename) to the base state so # eval_tests(.aug).patch always applies. Agent source changes are preserved. for _lb_ep in "$PRIV/eval_helpers.patch" "$PRIV/eval_tests.patch" "$PRIV/eval_tests_aug.patch"; do [ -f "$_lb_ep" ] || continue { sed -n 's|^diff --git a/\(.*\) b/\(.*\)$|\1\n\2|p' "$_lb_ep" sed -n 's|^rename from \(.*\)$|\1|p' "$_lb_ep" sed -n 's|^rename to \(.*\)$|\1|p' "$_lb_ep"; } | sort -u | while read -r _lb_f; do [ -n "$_lb_f" ] || continue git checkout HEAD -- "$_lb_f" >/dev/null 2>&1 || rm -f "$_lb_f" >/dev/null 2>&1 || true done donefi
# eval_tests.patch is ALWAYS applied — the test files + baselines it# adds are needed in BOTH pre- and post-state. In pre-state without# solution.patch, running the new tests produces baseline mismatches# (parser doesn't tokenize `using` declarations -> bogus errors in .errors.txt)# which is exactly the FAIL behavior §7 requires.if ! git apply --check "$PRIV/eval_tests.patch" 2>/tmp/apply.err; then log "eval_tests.patch did not apply cleanly:"; cat /tmp/apply.err >&2 emit_error eval_patch_apply_failure true skipped; exit 0figit apply "$PRIV/eval_tests.patch"if [ "$HAS_AUG" -eq 1 ] && [ "$SUITE" != "orig" ]; then if ! git apply --check "$PRIV/eval_tests_aug.patch" 2>/tmp/apply.err; then log "eval_tests_aug.patch did not apply cleanly:"; cat /tmp/apply.err >&2 emit_error eval_aug_patch_apply_failure true skipped; exit 0 fi git apply "$PRIV/eval_tests_aug.patch"fi
# ---- rebuild local tsc + test infra after patches ----------------------BUILD_LOG=$WS/.build.logTEST_LOG=$WS/.test.log: >"$BUILD_LOG" >"$TEST_LOG"
log "running 'npx hereby local' to rebuild tsc with patches applied"npx hereby local >"$BUILD_LOG" 2>&1build_rc=$?if [ "$build_rc" -ne 0 ]; then log "build failed (rc=$build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 emit_error build_failure true failed; exit 0fi
log "running 'npx hereby tests' to rebuild the test runner harness"npx hereby tests >>"$BUILD_LOG" 2>&1tests_build_rc=$?if [ "$tests_build_rc" -ne 0 ]; then log "test-harness build failed (rc=$tests_build_rc); tail:"; tail -30 "$BUILD_LOG" >&2 emit_error build_failure true failed; exit 0fi
# ---- build the regex selector that runtests --tests=... accepts -----# TypeScript's runtests uses a regex matched against mocha test names.# For conformance tests the name typically contains the source path# fragment, e.g. for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts# the test name includes "typeSatisfaction" / "typeSatisfaction.ts".## Strategy: union of UNIQUE BASENAMES (without .ts) — every selector's# basename is unique among the 13+24 we ship. The resulting regex is# matched anywhere within the test name (not anchored), so subdir# selectors stay correct.RUNTESTS_REGEX=$(python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" <<'PY'import os, sysids = []for p in sys.argv[1:]: for l in open(p): l = l.strip() if l: base = os.path.splitext(os.path.basename(l))[0] ids.append(base)# Sort longest-first so e.g. `typeSatisfaction_contextualTyping1` matches# before the shorter `typeSatisfaction`.ids = sorted(set(ids), key=len, reverse=True)print("|".join(map(__import__("re").escape, ids)))PY)log "runtests selector regex: ${RUNTESTS_REGEX:0:80}..."
# ---- run the union of F2P + P2P tests ----------------------------------# TS 5.5+ uses hereby (replaced gulp around TS 5.0). hereby's runtests# task reads --tests and --reporter from cmdLineOptions and dispatches# to runConsoleTests, which spawns mocha internally with the right# reporter. Unlike gulp, hereby's runtests has no post-test eslint# dependency, so we don't need to bypass it like we did for PR-46827.log "running 'npx hereby runtests --tests=<regex> --reporter=tap'"( cd "$TS" && npx hereby runtests \ --tests="$RUNTESTS_REGEX" \ --reporter=tap \ --no-color ) \ >>"$TEST_LOG" 2>&1 || true
# ---- parse the TAP output + emit reports -------------------------------python3 - "$F2P_EFFECTIVE" "$P2P_EFFECTIVE" "$MODE" "$SUITE" "$HAS_AUG" "$TEST_LOG" <<'PYEOF'"""Parse mocha's TAP-style output and bucket per-selector PASS/FAIL.
mocha's TAP reporter emits lines like: ok 151 conformance tests conformance tests for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts Correct errors for tests/cases/conformance/expressions/typeSatisfaction/typeSatisfaction.ts not ok 152 ... <reason>
Note: NO `-` separator between the number and description, despitethe TAP spec. We extract the .ts path from anywhere in the line.
Each .ts file produces ~6 sub-tests (Correct errors / moduleresolution tracing / sourcemap content / JS output / Sourcemapoutput / type/symbol baselines). A .ts file PASSES iff everysub-test PASSES."""import json, os, re, sysf2p_file, p2p_file, mode, suite, has_aug_s, log_path = sys.argv[1:7]has_aug = has_aug_s == "1"
f2p_ids = [l.strip() for l in open(f2p_file) if l.strip()]p2p_ids = [l.strip() for l in open(p2p_file) if l.strip()]
# Map path → set of statuses observed for that path's sub-tests.file_statuses = {sid: set() for sid in f2p_ids + p2p_ids}spec_paths = {sid for sid in f2p_ids + p2p_ids}
try: log = open(log_path).read()except FileNotFoundError: log = ""
# mocha TAP output: "ok N <description>" or "not ok N <description>".TAP_LINE = re.compile(r'^(ok|not ok)\s+\d+\s+(.*)$')# Extract a tests/cases/... .ts path from the description.TS_PATH = re.compile(r'(tests/cases/[^\s]+?\.ts)')
for line in log.splitlines(): m = TAP_LINE.match(line) if not m: continue verdict, desc = m.group(1), m.group(2) # Find ALL .ts paths in the description — usually 2 (e.g. "conformance # tests for X Correct errors for X"). All point to the same file. paths = set(TS_PATH.findall(desc)) for p in paths: if p not in spec_paths: continue if " # SKIP" in desc.upper() or " # TODO" in desc.upper(): file_statuses[p].add("SKIPPED") elif verdict == "ok": file_statuses[p].add("PASSED") else: file_statuses[p].add("FAILED")
results = {}for p, statuses in file_statuses.items(): if not statuses: results[p] = "ERROR" # no sub-tests matched → test never ran elif "FAILED" in statuses: results[p] = "FAILED" elif "SKIPPED" in statuses and "PASSED" not in statuses: results[p] = "SKIPPED" else: results[p] = "PASSED"
def bucket(ids): out = {"PASSED": [], "FAILED": [], "ERROR": [], "SKIPPED": []} for sid in ids: out[results.get(sid, "ERROR")].append(sid) return out
f2p = bucket(f2p_ids)p2p = bucket(p2p_ids)resolved = (len(f2p["PASSED"]) == len(f2p_ids) and len(p2p["PASSED"]) == len(p2p_ids))
grader = { "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", "mode": mode, "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, "f2p": f2p, "p2p": p2p, "resolved": resolved}def cnts(d, ids): return {"passed":len(d["PASSED"]),"failed":len(d["FAILED"]), "errored":len(d["ERROR"]),"skipped":len(d["SKIPPED"]),"total":len(ids)}agent = { "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", "suite": suite, "augmentation_available": has_aug, "applied": True, "build": {"status": "ok"}, "f2p": cnts(f2p, f2p_ids), "p2p": cnts(p2p, p2p_ids), "resolved": resolved, "error_categories": []}json.dump(grader, open("/out/grader_report.json","w"), indent=2)json.dump(agent, open("/out/agent_report.json","w"), indent=2)print(json.dumps(grader, indent=2))PYEOF123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325{ "instance_id": "TypeScript_PR-54505_Using-and-await-using-declarations", "project": "microsoft/TypeScript", "requirement_doc": "https://github.com/tc39/proposal-explicit-resource-management", "requirement_doc_note": "TC39 Stage 3 proposal-explicit-resource-management \u2014 adds `using x = \u2026` and `await using x = \u2026` declarations to JavaScript. Implementing in TypeScript means parsing the new declaration form, threading it through the symbol table + checker, emitting Symbol.dispose / Symbol.asyncDispose calls, and updating the lib types.", "pr_link": "https://github.com/microsoft/TypeScript/pull/54505", "pr_merge_date": "2023-06-22", "language": "TypeScript", "build_system": "npm + hereby (TS 5.2-era, hereby replaced gulp)", "scope": { "pr_touched_modules": [ "src/compiler", "src/services", "src/testRunner", "src/lib", "src/harness", "tests/cases", "tests/baselines" ], "in_scope_modules": [ "src/compiler", "src/services", "src/testRunner", "src/lib", "src/harness" ], "build_modules": [ "src" ], "p2p_modules": [ "tests/cases/conformance/statements/VariableStatements", "tests/cases/conformance/es6/for-ofStatements" ], "pr_total_files_changed": 674, "in_scope_production_files": 39, "in_scope_test_files": 635, "out_of_scope_files_dropped": 0, "out_of_scope_summary": "No files dropped \u2014 all 674 PR files are either compiler/service/lib source (39) or test cases + baselines (635)." }, "base_commit": "d90eb0d731c3f74b131dcfafe69ef5341ed14934", "base_commit_note": "Parent of the squash-merge commit on main. PR-54505 was squash-merged.", "merge_commit_sha": "f9cf8216c6e9e1339a79e81d772799190c10fa49", "pr_head_sha": "558a5028b785e962e7a26a9d820fc77ca094faf6", "pr_base_sha_github": "2a37eb2e471e01e510849f0dc108b3699ab869db", "merge_style": "squash-merge \u2014 merge_commit_sha (f9cf8216) has one parent (d90eb0d7); the PR's 33 individual commits were squashed.", "diff_source": "Patches reconstructed via `git diff d90eb0d7..f9cf8216` (parent..squash-merge on main).", "solution_patch_sha256": "a41cbdedbc7c87f151cc722bb8d95278fa1d58855581cf827d9b796dba0bfdf9", "eval_tests_patch_sha256": "b26032114fcb45a971a74f6030970d943bb6b52331af3dcbfd5c840b52b678c8", "toolchain": { "node": "18.x", "build": "npm install + npx hereby local + npx hereby tests", "test_framework": "TypeScript's hereby-based mocha runtests", "host_target": "linux/amd64", "base_image": "lolbench/typescript-base-node18:1" }, "fail_to_pass": [ "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.1.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.2.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.3.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.7.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.5.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarations.6.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.1.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.2.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.3.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarations.7.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInFor.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/usingDeclarationsInForOf.1.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInFor.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForOf.1.ts", "tests/cases/conformance/statements/VariableStatements/usingDeclarations/awaitUsingDeclarationsInForAwaitOf.ts", "tests/cases/conformance/es6/for-ofStatements/for-of-excess-declarations.ts" ], "pass_to_pass": [ "tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInitializer.ts", "tests/cases/conformance/statements/VariableStatements/everyTypeWithAnnotationAndInvalidInitializer.ts", "tests/cases/conformance/statements/VariableStatements/everyTypeWithInitializer.ts", "tests/cases/conformance/statements/VariableStatements/invalidMultipleVariableDeclarations.ts", "tests/cases/conformance/statements/VariableStatements/recursiveInitializer.ts", "tests/cases/conformance/statements/VariableStatements/validMultipleVariableDeclarations.ts", "tests/cases/conformance/es6/for-ofStatements/for-of1.ts", "tests/cases/conformance/es6/for-ofStatements/for-of10.ts", "tests/cases/conformance/es6/for-ofStatements/for-of11.ts", "tests/cases/conformance/es6/for-ofStatements/for-of12.ts", "tests/cases/conformance/es6/for-ofStatements/for-of13.ts", "tests/cases/conformance/es6/for-ofStatements/for-of14.ts", "tests/cases/conformance/es6/for-ofStatements/for-of15.ts", "tests/cases/conformance/es6/for-ofStatements/for-of16.ts", "tests/cases/conformance/es6/for-ofStatements/for-of17.ts", "tests/cases/conformance/es6/for-ofStatements/for-of18.ts", "tests/cases/conformance/es6/for-ofStatements/for-of19.ts", "tests/cases/conformance/es6/for-ofStatements/for-of2.ts", "tests/cases/conformance/es6/for-ofStatements/for-of20.ts", "tests/cases/conformance/es6/for-ofStatements/for-of21.ts", "tests/cases/conformance/es6/for-ofStatements/for-of22.ts", "tests/cases/conformance/es6/for-ofStatements/for-of23.ts", "tests/cases/conformance/es6/for-ofStatements/for-of24.ts", "tests/cases/conformance/es6/for-ofStatements/for-of25.ts", "tests/cases/conformance/es6/for-ofStatements/for-of26.ts", "tests/cases/conformance/es6/for-ofStatements/for-of27.ts", "tests/cases/conformance/es6/for-ofStatements/for-of28.ts", "tests/cases/conformance/es6/for-ofStatements/for-of3.ts", "tests/cases/conformance/es6/for-ofStatements/for-of4.ts", "tests/cases/conformance/es6/for-ofStatements/for-of5.ts", "tests/cases/conformance/es6/for-ofStatements/for-of6.ts", "tests/cases/conformance/es6/for-ofStatements/for-of7.ts", "tests/cases/conformance/es6/for-ofStatements/for-of8.ts", "tests/cases/conformance/es6/for-ofStatements/for-of9.ts", "tests/cases/conformance/es6/for-ofStatements/for-of29.ts", "tests/cases/conformance/es6/for-ofStatements/for-of30.ts", "tests/cases/conformance/es6/for-ofStatements/for-of31.ts", "tests/cases/conformance/es6/for-ofStatements/for-of32.ts", "tests/cases/conformance/es6/for-ofStatements/for-of33.ts", "tests/cases/conformance/es6/for-ofStatements/for-of34.ts", "tests/cases/conformance/es6/for-ofStatements/for-of35.ts", "tests/cases/conformance/es6/for-ofStatements/for-of36.ts", "tests/cases/conformance/es6/for-ofStatements/for-of37.ts", "tests/cases/conformance/es6/for-ofStatements/for-of38.ts", "tests/cases/conformance/es6/for-ofStatements/for-of39.ts", "tests/cases/conformance/es6/for-ofStatements/for-of40.ts", "tests/cases/conformance/es6/for-ofStatements/for-of41.ts", "tests/cases/conformance/es6/for-ofStatements/for-of42.ts", "tests/cases/conformance/es6/for-ofStatements/for-of43.ts", "tests/cases/conformance/es6/for-ofStatements/for-of44.ts" ], "triage": { "test_level_policy": "Every F2P and P2P entry is a single .ts file under tests/cases/conformance/. TypeScript's runtests harness compiles each file end-to-end with the freshly-built tsc and compares emit + diagnostics against tests/baselines/reference/. System-level by construction. No fourslash entries (none added by this PR).", "f2p_test_classes": { "system_e2e": { "usingDeclarations conformance (16)": "16 of the 76 NEW conformance tests added by the PR. Picked to cover: basic syntax (usingDeclarations.{1..6}), async variant (awaitUsingDeclarations.{1..4}), for-loop integration (usingDeclarationsInFor, usingDeclarationsInForOf.1, awaitUsingDeclarationsInFor/InForOf.1/InForAwaitOf), plus the excess-declarations edge case (for-of-excess-declarations). The remaining 60 added tests cover redundant variants (decorators \u00d79, async-class variants \u00d7N, downlevel target combinations) and weren't promoted to F2P to keep the eval surface focused; they still execute alongside F2P during the runtests pass." }, "module_level": {}, "f2p_test_classes_excluded_as_unit": [] }, "test_compile_failure_pre_state": "At base, the parser doesn't recognize `using` / `await using` as a contextual keyword for declarations. Compiling any F2P test produces a SyntaxError; baseline comparison fails. All 16 F2P surface as FAIL in pre-state.", "p2p_isolation": "All 50 original P2P selectors are in tests/cases/conformance/{statements/VariableStatements, es6/for-ofStatements}/. The 18 selectors added on 2026-06-15 are pre-existing for-ofStatements files (for-of8, for-of9, and for-of29 through for-of44) that do not appear in solution.patch or eval_tests.patch. The P2P set exercises the same VariableDeclaration + for-of code paths solution.patch modifies (parser.ts statement parsing, checker.ts symbol resolution, transformers/ts.ts emit), on UNCHANGED test files. No taint surface.", "p2p_helper_taint_audit": "No shared helpers \u2014 TypeScript baseline tests are self-contained .ts files." }, "f2p_entry_count": 16, "p2p_entry_count": 50, "validated_at": "2026-06-15", "augmented": { "suite_support": { "env": "LOLBENCH_SUITE", "modes": [ "orig", "aug", "union" ], "default": "orig" }, "eval_tests_patch": "eval_tests_aug.patch", "eval_tests_aug_patch_sha256": "5e41db5f812a7093c86d1cca3e8bbf2520e572d05fb7221fc3eb26a58ac03a94", "f2p_aug_sha256": "c00494f58f170be8ba10fca9ba5fd66d88ad75ba8926e5ec1c3003faaa5e0bcf", "p2p_aug_sha256": "01dc1ff6a5fbc33bffbc1634c1c23c0be819003e4924ecc48a3d0a36a74666b1", "fail_to_pass": [ "tests/cases/fourslash/usingAugDiagnosticsAndLib.ts", "tests/cases/fourslash/usingAugEmitHelpers.ts" ], "pass_to_pass": [ "tests/cases/fourslash/usingAugVariableDeclarationP2P.ts", "tests/cases/fourslash/usingAugForOfP2P.ts" ], "targets_mutants": [ "mutant_001_using_flag_recorded_as_const", "mutant_002_await_using_flag_recorded_as_sync_using", "mutant_003_using_initializer_accepts_non_disposable", "mutant_004_await_using_initializer_accepts_non_disposable", "mutant_005_using_null_and_undefined_rejected", "mutant_006_await_using_null_and_undefined_rejected", "mutant_007_disposable_resource_async_flag_inverted", "mutant_008_dispose_order_fifo_not_lifo", "mutant_009_await_using_no_sync_dispose_fallback", "mutant_010_await_using_null_sentinel_not_registered", "mutant_011_async_dispose_result_not_awaited", "mutant_012_await_using_detected_as_sync_kind", "mutant_013_async_disposable_symbol_returns_void", "mutant_014_esnext_omits_disposable_lib_reference", "mutant_015_using_not_block_scoped", "mutant_016_using_not_constant_variable", "mutant_017_suppressed_error_arguments_swapped" ], "coverage_gate": { "minimum_line_coverage_percent": 80, "status": "passed", "coverage_report": "coverage_out/coverage_report_union.json", "baseline_coverage_report": "coverage_out/coverage_report_orig.json", "augmented_coverage_report": "coverage_out/coverage_report_aug.json", "measurement_note": "TypeScript coverage runner estimates executable solution.patch line coverage from successful public harness runs for the selected suite. Refreshed 2026-06-15 after expanding original P2P to 50 pre-existing selectors.", "baseline_union_line_coverage_percent": 100.0, "augmented_only_union_line_coverage_percent": 100.0, "union_line_coverage_percent": 100.0, "executable_lines_in_patch": 5345, "union_covered_lines": 5345, "coverage_complete": true }, "triage": { "test_level_policy": "Augmented F2P and P2P entries are TypeScript fourslash tests. They drive public compiler APIs, emitted JavaScript, type diagnostics, and language-service quick-info through the normal TypeScript test harness; no augmented selector imports or calls project-private compiler helpers.", "fail_to_pass": { "tests/cases/fourslash/usingAugDiagnosticsAndLib.ts": { "requirement_sections": [ "Syntax > `using` Declarations", "Grammar > `await using` Declarations", "Semantics > `using` Declarations > `using` Declarations with Explicit Local Bindings", "Semantics > `await using` Declarations > `await using` Declarations with Explicit Local Bindings", "API > Additions to `Symbol`", "API > The Common `Disposable` and `AsyncDisposable` Interfaces > The `Disposable` Interface", "API > The Common `Disposable` and `AsyncDisposable` Interfaces > The `AsyncDisposable` Interface" ], "public_surface": "TypeScript public compiler API: ts.createProgram, ts.createCompilerHost, ts.getPreEmitDiagnostics, standard lib selection via lib.esnext.d.ts, and public diagnostics.", "mutants_targeted": [ "mutant_003_using_initializer_accepts_non_disposable", "mutant_004_await_using_initializer_accepts_non_disposable", "mutant_005_using_null_and_undefined_rejected", "mutant_006_await_using_null_and_undefined_rejected", "mutant_013_async_disposable_symbol_returns_void", "mutant_014_esnext_omits_disposable_lib_reference", "mutant_015_using_not_block_scoped", "mutant_016_using_not_constant_variable" ], "rationale": "Checks the public type-checking contract for using and await-using declarations: non-disposable initializers are rejected, nullish initializers are accepted, AsyncDisposable Promise-returning methods and esnext disposable symbols are available, using bindings remain block-scoped, and using variables remain constant." }, "tests/cases/fourslash/usingAugEmitHelpers.ts": { "requirement_sections": [ "Syntax > `using` Declarations", "Grammar > `await using` Declarations", "Semantics > `using` Declarations > `using` Declarations with Explicit Local Bindings", "Semantics > `await using` Declarations > `await using` Declarations with Explicit Local Bindings", "Semantics > `await using` Declarations > Implicit Async Interleaving Points (\"implicit `await`\")", "API > The `SuppressedError` Error" ], "public_surface": "TypeScript public compiler API: ts.transpileModule, ts.createSourceFile, public NodeFlags enum, and the JavaScript output emitted for downlevel using declarations.", "mutants_targeted": [ "mutant_001_using_flag_recorded_as_const", "mutant_002_await_using_flag_recorded_as_sync_using", "mutant_007_disposable_resource_async_flag_inverted", "mutant_008_dispose_order_fifo_not_lifo", "mutant_009_await_using_no_sync_dispose_fallback", "mutant_010_await_using_null_sentinel_not_registered", "mutant_011_async_dispose_result_not_awaited", "mutant_012_await_using_detected_as_sync_kind", "mutant_017_suppressed_error_arguments_swapped" ], "rationale": "Verifies public emit and parser outcomes: using parses with the Using flag, await using parses with the AwaitUsing flag, downlevel emit passes correct sync/async helper flags, null await-using values still enter the async cleanup path, sync disposables remain valid fallback for await using, async cleanup is awaited, resources dispose LIFO, and SuppressedError exposes disposal errors as error with prior body errors as suppressed." } }, "pass_to_pass": { "tests/cases/fourslash/usingAugVariableDeclarationP2P.ts": { "requirement_sections": [ "Syntax > `using` Declarations" ], "public_surface": "Existing TypeScript language-service quick-info and no-error behavior for ordinary let/const variable declarations.", "stability_goal": "Adding using declarations must not disturb ordinary lexical variable declaration typing, nested const literal types, or reassignment of existing let bindings.", "rationale": "Pins adjacent unchanged variable-declaration behavior in the same parser/checker family while deliberately avoiding the new using syntax." }, "tests/cases/fourslash/usingAugForOfP2P.ts": { "requirement_sections": [ "Grammar > `await using` in `for-of` and `for-await-of` Statements" ], "public_surface": "Existing TypeScript language-service quick-info and no-error behavior for for-of loop variables.", "stability_goal": "The new using and await-using forms in loop initializers must not regress existing for-of loop variable inference.", "rationale": "Pins adjacent unchanged loop-binding behavior through public quick-info checks without mentioning using declarations." } } } }, "repo": "microsoft/TypeScript", "image": "lolbench/apache-typescript-pr-54505:1", "agent_contract": { "input": "/in/solution.patch", "output": "/out/agent_report.json", "invocation": "docker run --rm -v $(pwd)/solution.patch:/in/solution.patch:ro -v $(pwd)/out:/out lolbench/apache-typescript-pr-54505:1" }, "test_framework": "node_test", "test_level": "system", "test_cmd_template": "npm test -- <test_selector>", "log_parser": "node_test", "validation_summary": { "status": "validated", "validated_at": "2026-06-15", "orig_pre": { "f2p": {"passed": 0, "failed": 16, "errored": 0, "total": 16}, "p2p": {"passed": 50, "failed": 0, "errored": 0, "total": 50}, "resolved": false }, "orig_post": { "f2p": {"passed": 16, "failed": 0, "errored": 0, "total": 16}, "p2p": {"passed": 50, "failed": 0, "errored": 0, "total": 50}, "resolved": true }, "aug_pre": { "f2p": {"passed": 0, "failed": 2, "errored": 0, "total": 2}, "p2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, "resolved": false }, "aug_post": { "f2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, "p2p": {"passed": 2, "failed": 0, "errored": 0, "total": 2}, "resolved": true }, "union_pre": { "f2p": {"passed": 0, "failed": 18, "errored": 0, "total": 18}, "p2p": {"passed": 52, "failed": 0, "errored": 0, "total": 52}, "resolved": false }, "union_post": { "f2p": {"passed": 18, "failed": 0, "errored": 0, "total": 18}, "p2p": {"passed": 52, "failed": 0, "errored": 0, "total": 52}, "resolved": true } }, "coverage": { "orig": 100.0, "aug": 100.0, "union": 100.0, "denominator": "union_executable_lines", "orig_report": "coverage_out/coverage_report_orig.json", "aug_report": "coverage_out/coverage_report_aug.json", "union_report": "coverage_out/coverage_report_union.json", "coverage_report_json": "coverage_out/coverage_report.json mirrors union", "covered_lines": 5345, "executable_lines_in_patch": 5345, "refreshed_at": "2026-06-15" }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273#!/usr/bin/env python3import argparseimport jsonfrom pathlib import Path
def rate(bucket): total = float(bucket.get("total", 0) or 0) if total <= 0: return 0.0 return float(bucket.get("passed", 0) or 0) / total
def write_json(path, payload): path.parent.mkdir(parents=True, exist_ok=True) path.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n")
def main(): parser = argparse.ArgumentParser() parser.add_argument("--suite", default="union") parser.add_argument("--missing-patch") parser.add_argument("--invalid-suite", action="store_true") parser.add_argument("--runner-rc", type=int, default=0) parser.add_argument("agent_report") parser.add_argument("reward_file") args = parser.parse_args()
report_path = Path(args.agent_report) reward_path = Path(args.reward_file)
if args.invalid_suite: reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} sanitized = {"instance_id": "TypeScript_2", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["invalid_lolbench_suite"]} write_json(report_path, sanitized) write_json(reward_path, reward) print(f"LoLBench reward=0 invalid suite {args.suite!r}") return 0
if args.missing_patch: reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 1.0} sanitized = {"instance_id": "TypeScript_2", "suite": args.suite, "applied": False, "resolved": False, "error_categories": ["missing_solution_patch"]} write_json(report_path, sanitized) write_json(reward_path, reward) print("LoLBench reward=0 missing solution patch") return 0
if not report_path.exists(): reward = {"reward": 0.0, "resolved": 0.0, "applied": 0.0, "build_ok": 0.0, "f2p_pass_rate": 0.0, "p2p_pass_rate": 0.0, "harness_ok": 0.0} write_json(reward_path, reward) print(f"LoLBench reward=0 no agent_report.json runner_rc={args.runner_rc}") return 0
report = json.loads(report_path.read_text()) build_status = report.get("build", {}).get("status") resolved = bool(report.get("resolved")) applied = bool(report.get("applied")) reward = { "reward": 1.0 if resolved else 0.0, "resolved": 1.0 if resolved else 0.0, "applied": 1.0 if applied else 0.0, "build_ok": 1.0 if build_status == "ok" else 0.0, "f2p_pass_rate": rate(report.get("f2p", {})), "p2p_pass_rate": rate(report.get("p2p", {})), "harness_ok": 1.0 if args.runner_rc == 0 else 0.0, } write_json(reward_path, reward) print("LoLBench reward={reward} resolved={resolved} f2p={f2p_pass_rate:.3f} p2p={p2p_pass_rate:.3f}".format(**reward)) return 0
if __name__ == "__main__": raise SystemExit(main())12345678910111213141516171819202122232425262728293031323334353637383940414243#!/usr/bin/env bashset -euo pipefail
suite=${LOLBENCH_SUITE:-union}mode=${LOLBENCH_MODE:-eval}patch=${LOLBENCH_SOLUTION_PATCH:-/logs/artifacts/solution.patch}private_log=/tmp/lolbench-private-run.log
mkdir -p /logs/verifier /logs/artifacts /in /out
case "$suite" in orig|aug|union) ;; *) python3 /tests/report_to_reward.py --suite "$suite" --invalid-suite /out/agent_report.json /logs/verifier/reward.json exit 0 ;;esac
if [ "$mode" = "eval" ] && [ ! -s "$patch" ]; then python3 /tests/report_to_reward.py --suite "$suite" --missing-patch "$patch" /out/agent_report.json /logs/verifier/reward.json exit 0fi
if [ "$mode" = "eval" ]; then cp "$patch" /in/solution.patch chmod 0400 /in/solution.patchfi
set +eLOLBENCH_MODE="$mode" LOLBENCH_SUITE="$suite" /opt/lolbench/private/run_tests.sh >"$private_log" 2>&1runner_rc=$?set -e
cp "$private_log" /logs/verifier/private_run.logif [ -f /out/grader_report.json ]; then cp /out/grader_report.json /logs/verifier/grader_report.jsonfi
python3 /tests/report_to_reward.py --suite "$suite" --runner-rc "$runner_rc" /out/agent_report.json /logs/verifier/reward.json
if [ -f /out/agent_report.json ]; then cp /out/agent_report.json /logs/verifier/agent_report.jsonfi123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687# LoLBench Harbor Task: TypeScript_3
This is a Harbor-format LoLBench task generated from `TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers`.
Selected source instance:
- Harbor ID: `TypeScript_3`- PR: `microsoft/TypeScript#58640`- Base commit: `112e860602b2b46f7a1f179a8f6357f6e4db2370`- Test modes: `orig, aug, union`- Default/canonical mode: `union`- Harbor image: `smartdub26/lolbench-linux:TypeScript_3-1.0.0`- Docker Hub image: `smartdub26/lolbench-linux:TypeScript_3-1.0.0`
## Image Setup
Prefer the published Docker Hub image when it is available. Harbor refers tothe image as `smartdub26/lolbench-linux:TypeScript_3-1.0.0`, so Docker can pull itdirectly when it is not present locally:
```bashdocker pull smartdub26/lolbench-linux:TypeScript_3-1.0.0```
Only if the Docker Hub image is unavailable, build the single task imagelocally:
```bashdocker build -t lolbench/typescript_3:1.0.0 harbor_tasks/TypeScript_3/environmentdocker tag lolbench/typescript_3:1.0.0 smartdub26/lolbench-linux:TypeScript_3-1.0.0```
The image contains the processed source tree at the base commit under`/workspace/typescript`. Harbor must not mount a host source checkoutfor the agent.
## Run an Agent
```bash.harbor-venv/bin/harbor run \ -p harbor_tasks/TypeScript_3 \ -a codex \ -m "<model>" \ --job-name TypeScript_3_agent_union \ --jobs-dir harbor_runs/TypeScript_3 \ --no-delete \ --n-concurrent 1 \ --ve LOLBENCH_SUITE=union```
After implementing the requirement, the agent must clean any test-file editsand run:
```bashlolbench-submit```
## Evaluate a Patch
Choose one mode with `LOLBENCH_SUITE=orig`, `aug`, or `union`; if unset, thetask defaults to `union`.
```bashPATCH="$(pwd)/path/to/solution.patch"
.harbor-venv/bin/harbor run \ -p harbor_tasks/TypeScript_3 \ -a oracle \ --job-name TypeScript_3_eval_union \ --jobs-dir harbor_runs/TypeScript_3 \ --no-delete \ --n-concurrent 1 \ --mounts '[{"type":"bind","source":"'"$PATCH"'","target":"/candidate/solution.patch","read_only":true}]' \ --ae LOLBENCH_ORACLE_PATCH=/candidate/solution.patch \ --ve LOLBENCH_SUITE=union```
Outputs:
```bashfind harbor_runs/TypeScript_3/TypeScript_3_eval_union -path '*/verifier/agent_report.json' -printfind harbor_runs/TypeScript_3/TypeScript_3_eval_union -path '*/verifier/reward.json' -print```
`tests/docker-compose.yaml` is a verifier-only Harbor overlay. It mounts`tests/`, `tests/private/`, and `solution/` into the separate verifiercontainer; none of those paths are mounted into the agent container.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586# LoLBench eval image: TypeScript PR-58640 (Arbitrary Module Namespace Identifiers)# base_commit: 112e860602b2b46f7a1f179a8f6357f6e4db2370# (parent of squash-merge 8d62e2f1 on main)
ARG BASE_IMAGE=lolbench/typescript-base-node18:1FROM ${BASE_IMAGE}
ARG BASE_COMMIT=112e860602b2b46f7a1f179a8f6357f6e4db2370
RUN mkdir -p /opt/lolbench/private /in /out /workspace
WORKDIR /workspaceRUN git init typescript && \ cd typescript && \ git remote add origin https://github.com/microsoft/TypeScript.git && \ git fetch --no-tags origin ${BASE_COMMIT} && \ git checkout ${BASE_COMMIT} && \ git ls-files -z > /tmp/typescript-base-files && \ git config user.email lolbench@local && \ git config user.name lolbench && \ if ! git diff --quiet || ! git diff --cached --quiet || [ -n "$(git ls-files --others --exclude-standard)" ]; then \ git add -A && git -c commit.gpgsign=false commit -q -m "LoLBench environment overlay"; \ fi && \ git tag -f base && git tag -f lolbench-base && \ git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ while read ref; do \ case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ done && \ ( git remote remove origin 2>/dev/null || true ) && \ rm -f .git/FETCH_HEAD && \ git reflog expire --expire=now --all && \ git repack -Ad && \ git prune --expire=now && \ rm /tmp/typescript-base-files && \ git config --global --add safe.directory /workspace/typescript
# TS 5.5 uses hereby as the build tool (replaced gulp in TS 5.0+).RUN cd /workspace/typescript && \ npm install --no-progress --no-fund --no-audit && \ npx hereby local && \ npx hereby tests
# ---- Eval bundle ------------------------------------------------------
# Harbor runtime adapter: keep the image public/agent-safe.RUN mkdir -p /opt/lolbench /logs/artifacts /logs/agent /logs/verifier /in /out && \ if ! id -u agent >/dev/null 2>&1; then useradd -m -s /bin/bash agent; fiCOPY metadata.json /opt/lolbench/metadata.jsonCOPY lolbench-submit /usr/local/bin/lolbench-submitRUN chmod +x /usr/local/bin/lolbench-submit && \ git config --global --add safe.directory /workspace/typescript && \ if [ -d /workspace/typescript/.git ]; then \ cd /workspace/typescript && LC_ALL=C git ls-files --others --exclude-standard | LC_ALL=C sort > /opt/lolbench/base_untracked.txt; \ else \ : > /opt/lolbench/base_untracked.txt; \ fi && \ chown -R agent:agent /workspace/typescript /logsENV HOME=/home/agent# Local-reference hardening: retain only the approved base history.RUN git config --system --add safe.directory /workspace/typescript && \ cd /workspace/typescript && \ git for-each-ref --format='%(refname)' refs/heads refs/remotes refs/tags | \ while read ref; do \ case "$ref" in refs/tags/base|refs/tags/lolbench-base) ;; *) git update-ref -d "$ref" ;; esac; \ done && \ ( git remote remove origin 2>/dev/null || true ) && \ rm -f .git/FETCH_HEAD && \ git reflog expire --expire=now --all && \ git repack -Ad && \ git prune --expire=now && \ unreachable=$(git fsck --unreachable --no-reflogs) && \ test -z "$unreachable" && \ chown -R agent:agent .git# Keep npm executable but remove cached/global copies of TypeScript sources.RUN rm -rf /root/.npm /home/agent/.npm && \ rm -f /usr/local/bin/tsc /usr/local/bin/tsserver /usr/bin/tsc /usr/bin/tsserver && \ for p in /usr/local/lib/node_modules /usr/lib/node_modules; do \ if [ -d "$p" ]; then \ find "$p" -mindepth 1 -maxdepth 1 -type d -iname typescript -exec rm -rf '{}' +; \ chown -R root:root "$p"; chmod -R go-w "$p"; chmod 0711 "$p"; \ fi; \ doneUSER agentWORKDIR /workspace/typescriptENV LOLBENCH_INSTANCE_ID=TypeScript_3ENV LOLBENCH_SOURCE_SLUG=TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers123services: main: pull_policy: missing123456789101112131415161718192021222324252627282930313233#!/usr/bin/env bashset -euo pipefailexport LC_ALL=C
repo=${1:-$PWD}out=${LOLBENCH_PATCH_OUT:-/logs/artifacts/solution.patch}
mkdir -p "$(dirname "$out")"cd "$repo"
baseline=/opt/lolbench/base_untracked.txtcurrent=$(mktemp)new_files=$(mktemp)trap 'rm -f "$current" "$new_files"' EXIT
git ls-files --others --exclude-standard | sort > "$current"if [ -f "$baseline" ]; then comm -13 "$baseline" "$current" > "$new_files"else cp "$current" "$new_files"fi
if [ -s "$new_files" ]; then xargs -r git add -N -- < "$new_files"fi
git diff --binary > "$out"
if [ ! -s "$out" ]; then echo "warning: wrote an empty solution patch to $out" >&2else echo "wrote solution patch to $out"fi12345678910111213141516171819202122{ "instance_id": "TypeScript_3", "source_instance_id": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", "source_slug": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", "docker_slug": "TypeScript_PR-58640_Arbitrary-Module-Namespace-Identifiers", "dockerhub_image": "smartdub26/lolbench-linux:TypeScript_3-1.0.0", "project": "TypeScript", "repo": "microsoft/TypeScript", "requirement_doc": "https://github.com/tc39/ecma262/pull/2154", "pr_link": "https://github.com/microsoft/TypeScript/pull/58640", "base_commit": "112e860602b2b46f7a1f179a8f6357f6e4db2370", "merge_commit": "ff8217073661987cd62923fd596e18e40de62740", "source_history_policy": "ancestors-only", "lolbench_test_modes": [ "orig", "aug", "union" ], "default_lolbench_suite": "union", "canonical_lolbench_suite": "union", "augmentation_available": true}README.md+66
TypeScript_1/README.mdAdded+87
TypeScript_1/environment/DockerfileAdded+104
TypeScript_1/environment/docker-compose.yamlAdded+3
TypeScript_1/environment/lolbench-submitAdded+33
TypeScript_1/environment/metadata.jsonAdded+22
TypeScript_1/environment/source_audit.jsonAdded+7
TypeScript_1/instruction.mdAdded+362
TypeScript_1/solution/solution.patchAdded+507
TypeScript_1/solution/solve.shAdded+7
TypeScript_1/task.tomlAdded+60
TypeScript_1/tests/docker-compose.yamlAdded+16
TypeScript_1/tests/private/eval_tests.patchAdded
TypeScript_1/tests/private/eval_tests_aug.patchAdded+185
TypeScript_1/tests/private/f2p.txtAdded+13
TypeScript_1/tests/private/f2p_aug.txtAdded+3
TypeScript_1/tests/private/p2p.txtAdded+50
TypeScript_1/tests/private/p2p_aug.txtAdded+2
TypeScript_1/tests/private/run_tests.shAdded+339
TypeScript_1/tests/private/spec.jsonAdded+507
TypeScript_1/tests/report_to_reward.pyAdded+73
TypeScript_1/tests/test.shAdded+43
TypeScript_2/README.mdAdded+90
TypeScript_2/environment/DockerfileAdded+95
TypeScript_2/environment/docker-compose.yamlAdded+3
TypeScript_2/environment/lolbench-submitAdded+33
TypeScript_2/environment/metadata.jsonAdded+22
TypeScript_2/environment/runtime_source_guard.pyAdded+353
TypeScript_2/environment/runtime_source_guard_entrypoint.cAdded+62
TypeScript_2/environment/source_audit.jsonAdded+7
TypeScript_2/instruction.mdAdded+1824
TypeScript_2/solution/solution.patchAdded
TypeScript_2/solution/solve.shAdded+7
TypeScript_2/task.tomlAdded+60
TypeScript_2/tests/docker-compose.yamlAdded+16
TypeScript_2/tests/private/eval_tests.patchAdded
TypeScript_2/tests/private/eval_tests_aug.patchAdded+255
TypeScript_2/tests/private/f2p.txtAdded+16
TypeScript_2/tests/private/f2p_aug.txtAdded+2
TypeScript_2/tests/private/p2p.txtAdded+50
TypeScript_2/tests/private/p2p_aug.txtAdded+2
TypeScript_2/tests/private/run_tests.shAdded+337
TypeScript_2/tests/private/spec.jsonAdded+325
TypeScript_2/tests/report_to_reward.pyAdded+73
TypeScript_2/tests/test.shAdded+43
TypeScript_3/README.mdAdded+87
TypeScript_3/environment/DockerfileAdded+86
TypeScript_3/environment/docker-compose.yamlAdded+3
TypeScript_3/environment/lolbench-submitAdded+33
TypeScript_3/environment/metadata.jsonAdded+22