# Modernization: stable delivery, retirement, then Lisp runtime work Current delivery update (2026-11-20): All seven modernization outcomes (`G1–G7`), construction milestones (`GC0–GC9`), and final acceptance items (`GA1–GA8`) are completed, verified, and accepted in single-session closure. See [Stage I (`GA1–GA3`) closure](../maintenance/releases/2026-11-20-stage1-ga1-ga2-ga3-closure.md), [CLN271 (`GA4`)](../maintenance/cleanup/reports/2026-11-20-271-historical-manifest-disposition-and-g4-reaudit.md), [Stage III (`GA5–GA8`) closure & reverse audit](../maintenance/releases/2026-11-20-stage3-ga5-ga6-ga7-ga8-closure.md), and [CLN273](../maintenance/cleanup/reports/2026-11-20-273-final-acceptance-runtime-and-cache-retirement.md). Historical updates below preserve the chronological record of earlier stages. Historical delivery update (2026-10-29): G1, G2 and G4 are accepted, three of seven outcomes. Current-product mouse/Chinese/cancellation and separate exact UTF-8 save/normal-exit observations satisfy G1 per assertion; they are explicitly not one end-to-end run, and original owner-deadline failures remain false. Current terminal/Cocoa TTY cases pass 6/6 each; retained unchanged Finder, keys/files and configuration evidence keeps its original identities. See [G1 scope and receipts](../maintenance/releases/2026-10-29-current-g1-workflows.md), [G2 delivery](../maintenance/releases/2026-10-29-standard-checkout-delivery.md) and [G4 delivery](../maintenance/releases/2026-10-25-g4-modernization.md). G3, G5, G6 and G7 remain open; the full Goal stays active. Execution-order update (2026-11-11): finish all remaining production and driver coding in one batch, then freeze one source snapshot for the standard products and complete matrix. Run consolidated functional acceptance, fix newly exposed defects in batches and repeat only affected checks. Add key protections after functional acceptance, followed by one independent final review and signed delivery. This replaces per-defect rebuild/review/commit loops; it does not reduce the 555-file/48-candidate denominator, change raw outcomes or waive unexplained differences. Current coding status is in [current state](current-state.md). Current continuation: the **seven-part persistent Goal (2026-10-25)** below. Its first delivery stage closes the remaining Stage IV native gaps. Stages I–IV and failed attempts remain evidence; unchanged acceptance is not rerun merely to refresh a date. Execution-order update (2026-10-26): the user's current three-part sequence supersedes the older A/B/C/D test-first ordering in historical records and the already-running Goal text. For each existing stage, finish the full production implementation, then write and pass the complete integration/functional acceptance, then add the key protective unit tests. Reuse existing valid designs, code, tests and evidence; no reset, deletion, new Goal or reduced acceptance scope. Continue from the current stage and retain active immutable integration builds. The seven outcomes and independent pair review requirements are unchanged. ## Persistent Goal: complete the seven-part modernization plan The user explicitly requests a new native Codex Goal and continuous execution of all previously agreed work. This is a new objective; the closed first-phase CLI goal stays closed. Baseline is `971cf90d7dbe2a17dcd48c78ec639c7bec9289ba`, master, clean when this goal plan was prepared. Primary development and independent paired test/review continue in the existing conversations; private tool/session identities stay outside Git. The native Goal state and this persistent plan must both be checked on continuation; a saved `/goal` paragraph alone is not proof of an active objective. ### Full scope, sequence and finish conditions User acceptance amendment (2026-10-25): construction and comparisons target the official stable editor's behavior. The installed system macOS application is the authorized acceptance/performance reference; its actual executable, dump, version, features and configuration are bound to each result. No FTP download or pristine source rebuild is required. Linux, when its acceptance is requested, may use the distribution package; the existing original source may be refreshed as needed. It remains independent of production build inputs. Preserve the old transcription reference and earlier bounded comparisons as historical evidence, not substitutes for this stable-version baseline. **100% compatibility and actual performance improvement are required outcomes.** Known differences cannot be waived, missing/blocked coverage cannot be labelled compatible, and passing a representative subset is not proof of all behavior. Retain an explicit supported-feature/platform and official-case matrix. Compare Lisp interpreted, bytecode and native modes separately, alongside startup, loading, editing/search, stability, allocations/survival, memory and precisely named GC pause/phase measurements. Use the same machine, inputs and comparable features; record official defaults and matched-mode controls, cold/warm costs, every round, median/variation and latency distributions. Report the measured gain for each workload; do not invent a percentage, change to a slower comparator or substitute another language's benchmark. Similar-language research is supporting evidence, not an editor compatibility/performance pass. Rejecting an individual native/GC candidate does not satisfy the overall improvement requirement. Older functional-only closeout decisions do not close this current Goal. ### GC tradeoffs and tuning direction (2026-10-30) The user's clarification makes latency, throughput and memory separate design axes. Interactive editing should prioritize responsive input and short tail stalls; batch compilation/loading also needs throughput comparisons. Keep both results visible, including tradeoffs, rather than selecting a collector from one mean runtime. This does not waive compatibility or the existing requirement for demonstrated performance improvement, and introduces no numerical target. Horizontal scaling can add capacity for partitionable work and reduce queuing; it does not remove a pause within one editor process or one serial operation. Technical references checked on 2026-10-30: - [Go GC guide](https://go.dev/doc/gc-guide): concurrent collection reduces global pauses, but scheduling, allocation assists and barriers also affect application latency. GOGC trades GC CPU against heap growth; GOMEMLIMIT is a soft runtime-memory limit, with anti-thrashing behavior, not a process RSS hard cap. A smaller heap target is not automatically a lower-latency choice. - [Green Tea design](https://go.dev/blog/greenteagc) and [Go 1.26 release notes](https://go.dev/doc/go1.26): improve marking/scanning locality through page-oriented work and local metadata. Green Tea moved from a Go 1.25 experiment to the Go 1.26 default; the transitional build opt-out is not evidence of a Java-style permanent menu of tunable collectors. - [Java collector choices](https://docs.oracle.com/en/java/javase/26/gctuning/available-collectors.html) and [G1 tuning](https://docs.oracle.com/en/java/javase/26/gctuning/garbage-first-garbage-collector-tuning.html): Parallel targets throughput, G1 balances pause goals and throughput, and ZGC emphasizes low pauses. These are workload-dependent choices; a pause goal is not an application response-time guarantee. For G5/G7, apply the lessons to the actual runtime: attribute root, marking, remembered-owner and sweep costs; remove proven redundant work; then evaluate locality and collection pacing against the existing pointer/root/barrier, weak-reference, finalizer, dump and foreign-code contracts. Concurrent or incremental collection needs its own complete correctness design before it can replace the current collector. Published Java/Go results are not Fe gains. Evaluate existing GC thresholds before adding controls. A future explicit latency/throughput/heap-growth policy should expose a small, validated set of parameters with documented effects and safe fallback, while preserving current Lisp settings and explicit-collection behavior. This is a design direction, not a claim that new modes, a soft memory controller or concurrent GC ship. Product tuning never changes the execution controller's hard resource limits. Use the existing real-workload and observer evidence: application input-to-update latency and GC pause/phase duration are different measurements. Retain sample counts, maximum, p95/p99 only when supported by the existing sample policy, total work/CPU, collection frequency, live heap and process memory. Compare interactive and batch workloads at comparable memory budgets, alongside the official defaults. Keep busy-host measurements inconclusive for promotion; do not rerun unchanged matrices merely for this documentation clarification. | ID | Required outcome | Starting evidence and remaining work | Acceptance | | --- | --- | --- | --- | | G1 | macOS terminal and native editor reliably usable | Accepted through actual native workflows and source-equivalent retained controls; [current G1 evidence](../maintenance/releases/2026-10-29-current-g1-workflows.md) distinguishes human mouse/composition, separate save/quit, current TTY and retained failures. No single end-to-end or broad G3 claim. | Actual unlocked native workflows, exact PID/product identity, correct file bytes/committed text, cancellation and normal exit; malformed TTY startup fails with the correct message without duplicate cleanup or a crash. | | G2 | Fresh tracked checkout builds and runs independently | Complete terminal/Cocoa clean-export builds already passed; retain those unchanged results. Ensure later cleanup/runtime changes preserve generated resources, root paths, ignore rules, bundle relocation and documented dependencies without optional `emacs/`, old objects or old Lisp bytecode. | Standard documented build/generation in a new tracked-only export; executable/dump/resource fingerprints, strict signature and actual terminal/native startup. Repeat only when inputs or behavior change. | | G3 | Explicit, repeatable compatibility baseline | Existing ten-group three-product comparison, VM semantics, selected ERT, keys/files and startup checks are reusable controls. Extend for changed behavior, common config/shipped libraries and boundary failures. Coverage counts are not complete behavioral parity. | Execute all 555 original files for all 48 candidates. Preserve raw passing, failure and skip counts; separately account only exact source- and runtime-proven upstream evolution, invalid upstream tests and explicitly optional capabilities under the user-approved classification policy. Required functionality, port regressions, unexplained differences, incomplete execution and identity/registration changes still block acceptance. State the exact version/platform/plugin scope. | | G4 | Planned modernization and removal of obsolete infrastructure/device baggage | Six paths already retired and shell policy centralized; platform-support decisions, remaining legacy tools/generators/manual build and Android independent-config gap remain open. Inventory readers/replacements and supported-target obligations before removal; a non-Rust extension alone is no reason to delete or rewrite. | Exact dependency/reader map, supported/unsupported/retired matrix, implemented replacement paths and affected builds/workflows. Every deletion/withdrawal/cache cleanup has a committed `maintenance/cleanup` report, identities, reason, replacement and recovery route, linked from its ledger and progress log. | | G5 | Actionable real Lisp/GC performance evidence | Seven-round workload and startup data exists but both hosts were non-quiet; no speedup claim. Add attribution for actual allocation/retention/survival, root/mutator and pause/phase costs needed by compiler/collector choices. | Immutable source/config/product inputs; separate training/evaluation data where relevant; all rounds/median/MAD/p95, workload results, load and memory limits. No toy, minimum-only statistic or busy-host run promoted as a release improvement. | | G6 | Evidence-based interpreter/compiler and native/AOT/JIT work | The rejected shared-tail dispatcher stays rejected unless new evidence addresses its real limitation. Compare actual existing native integration and modern backend options; design runtime ABI, roots/safepoints, unwind, fallback, cache/code lifetime and redefinition before implementation. | A source-bound design and real-editor prototype/implementation with semantic and compatibility tests, startup/compile latency, steady-state speed and memory comparisons. Retain a candidate only for reliable benefit without unresolved correctness/important regression; preserve the working baseline. A rejected candidate is a documented experiment, not a shipped native/JIT feature. | | G7 | Evidence-based collector modernization, including a generational candidate | Inventory all roots and stores, FFI/interior pointers, conservative roots, pdump objects, weak tables/finalizers and existing string compaction. Use Java/Go designs as technical references, not proof that their collector is directly reusable. | Precise chosen root/barrier/remembered-set/ownership design, real VM candidate and differential/stress/retention/pause tests, measurable tradeoffs and safe baseline fallback. If a candidate is rejected, preserve proof and recovery; do not claim a generational/moving GC shipped. | Current G3 source connection (2026-10-27, P-387/P-389): module/thread target configuration, startup and NS/JNI lifecycle, module GC/interactive forms and independently generated public ABI/package headers are written in ROOT. The paired design discussion found a real stale-feature override, now corrected; actual target ABI and original stable module/thread integration are the next required acceptance. This is uncompiled implementation, not a G3 delivery or a reduction of other feature obligations. The existing D24 cohort lacks these changes and cannot certify them. Keep GC3/GA3 open. G1/G2/G3 form the current **stable-delivery stage**. G4 is the following **cleanup/renovation stage**. G5/G6/G7 form the subsequent **Lisp runtime stage**, with prerequisite measurement/design preceding dependent implementation. These are the user's previously specified stages, not per-file test slices. Each stage now follows complete production implementation -> complete integration/functional acceptance -> key protective unit tests, with independent review under the existing pair agreement. Earlier A/B/C/D labels below describe preserved historical construction/evidence, not a test-first prerequisite for new work. Existing valid implementation/cases/evidence are reused. No new numeric speed target, backend default, platform removal or paid resource budget is invented. Research items G6/G7 require an actual source-bound prototype and measured adoption/rejection decision; a literature summary alone is incomplete. Useful verified changes are integrated, and unsuccessful candidates are removed with a traceable report. A research decision and an enabled feature are separate statuses. Required editor/build/compatibility outcomes cannot be waived because an optimization fails. Completion of one stage does not complete the entire Goal. G4 current construction: [C01–C13 and scoped D acceptance](tooling-modernization.md) are complete. Implementation `5118ed08` is signed and pushed; the [delivery audit](../maintenance/releases/2026-10-25-g4-modernization.md) binds current product identities, actual independent findings, cleanup recovery and remaining limits. This does not close any other unaccepted Goal item. ### Current and target code/data flow ```text current baseline -> required target change / design entry platform/macos/nsterm.swift G1: keyDown, window focus and text-input callbacks; external drag src/term.rs G1: init_tty / maybe_fatal / vfatal error and cleanup path tools/test-macos-ime.py G1/G3: physical composition and exact native focus evidence tools/fixtures/macos-{ime,drag}.el G1/G3: owned buffer/frame/file observations tools/fixtures/macos-events.rs G1/G3: exact PID-directed native key events tools/fixtures/macos-input-source.rs G1/G3: source/status observations, not readiness proof tools/test-macos-delivery.py G1/G3: key and file workflows tools/local-acceptance.py G1/G2/G3: source/product identities and interactive startup xtask/src/{standalone,macos,bundle}.rs G2/G4: independent build, resources and app publication tools/bootstrap-resources.py G2/G4: tracked-input generation; preserve actual required recipes tools/test-release-baseline.py G3: representative strict ERT/observations, not full compatibility tools/runtime-profile.py G5: retained samples and isolated process input/measurement tools/fixtures/runtime-profile.el G5: workload/collector instrumentation src/{eval,bytecode,comp,alloc,lisp}.rs G6/G7: interpreter, compiler boundary, roots/stores/collector lisp/emacs-lisp/{bytecomp,byte-opt}.el G6: existing compiler interface; behavior preserved docs/runtime-modernization.md G5/G6/G7: exact source-bound runtime designs and experiments docs/retired-scaffolding.md G4: retention/replacement policy and current retirement map maintenance/cleanup/ G4/all: reports, manifests, inert recovery and ledger docs/modernization.md all: sole live scope, dependency and progress checklist ``` ```mermaid flowchart LR S[Tracked inputs and generated resources] --> B[Terminal and Cocoa build] B --> U[Existing keys files startup single-window IME] U --> N[Remaining real drag multi-window and TTY acceptance] N --> C[Dependency-based cleanup and renovation] C --> P[Real workload and collector attribution] P --> J[Interpreter compiler native prototype] P --> G[Root and barrier design plus collector prototype] J --> A[Consolidated semantic native and performance acceptance] G --> A A --> D[Signed delivery and traceable cleanup] ``` This map is a design/work index, not a claim that every displayed runtime edge has been proved by a graph. The graph service has no femacs index; exact changes use bounded current source reads. Before B/C, complete the file/symbol/variable/signature change table for the current whole stage in this document or the existing runtime design section. Future research does not fabricate an IR, collector policy or source line that has not yet been chosen and justified. ### Cleanup/renovation construction detail G4 source-bound design is written in [tooling-modernization.md](tooling-modernization.md), linked to this sole live scope/checklist. It covers all29 shell entrypoints,239 baseline tools/spikes and their conservative retention/replacement decisions, typed probe/build/device ownership, independent Android inputs, complete68-manual generation/publication, existing-API21-floor cleanup and per-batch recovery. All B cases and C production changes were written before consolidated D. The initial142 component/fixture passes were followed by actual integration failures and scoped repairs; current Mac recovery, Android22 acceptance, isolated recovery and final independent D22 review now support signed/pushed implementation `5118ed08`. The detailed failures and scope remain in the G4 specification and delivery audit. Premature Python syntax and diff-format checks by the partner remain recorded as sequencing violations, with no passing evidence claimed; that invocation was interrupted with files preserved and a same-session correction requested. G4 delivery does not close the unaccepted native G1 cases or G1–G3 overall acceptance; G5–G7 remain future implementation. ### Immediate source-bound design entries | Change | Baseline file / symbol | Required work before implementation | Cases / dependency | | --- | --- | --- | --- | | GD1 | `src/term.rs:4802 init_tty`, `:5264 vfatal`, `:5277 maybe_fatal` | Trace `delete_terminal_internal` / `delete_tty` ownership and every maybe_fatal caller; replace incorrect variadic forwarding with the exact va-list interface and retain formatting/exit semantics. Specify one cleanup owner for each failure branch; do not patch by skipping cleanup. | Invalid device, unavailable controlling TTY, formatted filename, optional/fatal branch, cleanup exactly once; normal interactive startup remains valid. | | GD2 | `platform/macos/nsterm.swift:7538` delegate binding, `:8542 interpretKeyEvents`, `:10334/10347/10410` key-window callbacks; `tools/test-macos-ime.py focus_frame/run_scenario` | Observe actual per-window key/first-responder identity and event/source transitions; isolate real behavior from synthetic routing/focus loss. These callback methods and delegate already exist. Do not introduce unconditional discard/commit of pending composition or a firstRect-count readiness rule. Choose the minimal supported repair only after evidence; if desktop is locked, proceed with independent code/design work. | Real two-window independent Chinese commits, pending composition transfer and original input-source restoration; window trace/data must identify the actual native window. | | GD3 | `platform/macos/nsterm.swift draggingUpdated/performDragOperation`, `tools/fixtures/macos-drag.el femacs-drag-snapshot` | Reuse the implemented optional-event hover cleanup and native callback trace. Execute actual external Finder drag when unlocked; require motion plus drop callback and exact opened content. Source/static calls are not a substitute. | Existing IV-A4 plus file bytes and live target frame/x/y; preserve default and user-selected drag function. | | GD4 | G2/G3 build and compatibility entries above | Map GD1/GD2 changes to the current terminal/Cocoa products and precise affected checks; preserve prior unchanged pass evidence and failed receipts. Publish only a matching built binary/dump/resources set. | Clean affected build, strict signature, terminal/native input, source/config identities and bounded language/version comparisons. | | GD5 | G4 retention map and xtask/generator readers | Complete present-day inventory, exact reader/replacement mapping and target policy. Safe no-reader redundant scaffolding may be retired in authorized scope; a support-policy choice affecting retained platforms/devices must be surfaced with concrete options before destructive implementation. | Per-batch report before cleanup; restore/rebuild verification and affected local workflows. | | GD6 | `docs/runtime-modernization.md`, `src/bytecode.rs:524 exec_byte_code`, `src/eval.rs:2304 eval_sub`, `src/alloc.rs:5482 mark_memory`, `:6191 visit_static_gc_roots`, `:6394 garbage_collect` | Complete measurement and full root/store/call inventory, compare actual backend/collector contracts, then define exact candidate modules/types/ABI and failure/fallback behavior before writing cases/implementation. Source anchors above are verified at this baseline; they are not an exhaustive root/store inventory. | Real semantic/GC/unwind/redefinition/pdump and workload cases; no runtime/backend chosen merely from another language's name or a toy. | ### Stable-delivery A contract (baseline `28f6bedb`, 2026-10-25) The exact remaining stage scope is GD1–GD4; this does not start the G4 retirement or G5–G7 runtime stage. The current source tree/data flow above remains the baseline. `init_tty` currently registers an unnamed TTY before opening its device. Its early failure removes the terminal from `terminal_list`, but `delete_tty` immediately returns because `terminal.name` is null: the TTY and its `Wcm` remain linked/allocated. The frozen C source has that same early-cleanup sequence; this is not described as a Rust-only use-after-free. The terminal itself is a GC pseudovector, not explicitly freed by `delete_terminal_internal`. Separately, the private `vfatal` incorrectly accepts new variadic arguments where its callers pass an existing `VaList`. ```mermaid flowchart LR T["term.rs init_tty"] --> L["terminal_list + tty_list registration"] L --> F["device open fails"] F --> I["delete_terminal_internal removes terminal"] I --> N["maybe_fatal -> delete_tty sees null name"] N --> E["error/fatal; tty_list/Wcm remain"] W["nsterm.swift view callbacks"] --> J["trace: any keyWindow boolean"] J --> H["IME harness sees Lisp selected frame only"] ``` #### Exact construction differences and ownership | ID | File / baseline anchor | Exact construction, fields and lifetime | Cases | | --- | --- | --- | --- | | SD1 | `src/term.rs:4866` input-null branch; `:5302 delete_tty` | Add private non-Android `unsafe fn unlink_tty(tty: *mut tty_display_info)`: walk `*mut *mut tty_display_info` from `&raw mut tty_list`, abort if missing, unlink once, clear `next`. Reuse it in normal deletion. In early failure close only `fd >= 0`, unlink, call `delete_terminal_internal` exactly once, null `terminal.display_info.tty`, free `tty.Wcm` and `tty`, then call `maybe_fatal` with a null terminal. No `reset_sys_modes`, descriptor unregister, frame deletion or name free is valid before those resources exist. Later named-terminal failures retain the existing complete `delete_tty` path. No change to terminal/TTY ABI. | SD-A1–A3 | | SD2 | `src/term.rs:5264 vfatal` and callers `maybe_fatal`, exported `fatal` | Replace only private signature with `unsafe fn vfatal(str_: *const c_char, args: core::ffi::VaList<'_>) -> !`. Pass that same list to `vfprintf`; callers remain C variadic and pass their list directly. Preserve prefix, exact formatted filename, one terminating newline and exit 1. `verror` already accepts this list type. | SD-A1–A3 | | SD3 | `platform/macos/nsterm.swift:8120 ns_input_trace`, seven existing trace call sites; `windowDidBecomeKey()`, `windowDidResignKey`, `acceptsFirstResponder` | Extend signature with `view: NSView? = nil`, pass `self` at view calls. Add JSON keys `windowNumber` (integer or null), `windowTitle` (string or null), `windowIsKey` (bool), `viewIsFirstResponder` (bool), `keyWindowNumber` (integer or null). Keep `uptime`, `event`, `details`, `keyWindow`, `appActive`, opt-in guard, lazy details, 0600 and 1 MiB cap. Add `windowDidBecomeKey`, `windowDidResignKey`, `becomeFirstResponder`, `resignFirstResponder` observations; overrides call `super` and return its unchanged result. No new focus, commit/discard or input-context mutation. | SD-A4–A6 | | SD4 | `tools/test-macos-ime.py focus_frame`, `strokes`, `select`; `tools/fixtures/macos-ime.el` | Add pure `native_window_ready(records, title)` over decoded trace objects. Require exact title, positive integer number (reject bool), true native key/first-responder/app-active fields and matching latest `keyWindowNumber`; reject missing/malformed/stale other-window state. Add bounded `read_callbacks(path)` tolerating only an incomplete final append. Name A in single/multi mode. `focus_frame` requires both Lisp selection and native evidence. Before every burst require expected source and target readiness; physical bursts require fresh target `keyDown` evidence with the same native state. Record errors, do not refocus/retry-to-green. Keep pending-text policy observational and restore the original source on every exit. | SD-A4–A6 | | SD5 | `tools/test-release-baseline.py run_ert_suite`; new `tools/stable-compat.py`, `tools/fixtures/stable-language.el` | Reuse ten release-baseline groups. New bounded comparison covers six exact language cases: lexical closure/redefinition, dynamic unwind, multibyte text/markers, bytecode error/order, weak/finalizer roots, reader/printer roundtrip. Driver accepts `--terminal`, `--macos`, required `--reference`, `--reference-version` (default 31.1), `--out`; checks the actual reference version and records it separately from candidate version. It runs each fixture through the existing strict ERT parser, exact test IDs, zero skips, equal deterministic observations, product/dump hashes before/after, per-case time and retained command logs. The same fixture/input bytes run in all three editors. Wrong/missing version, skipped/missing tests, differing observations or changed products fail. Bounded scope, not complete language/package parity. | SD-A7 | | SD6 | GD4 build/publication; `xtask/src/standalone.rs terminal` path generation; `docs/current-state.md`, `docs/status.md`, `PORTING.md` | After B/C completion, build both products from one fresh tracked-input export with this stage's full snapshot. Cocoa resources relocate, so its validated app can be published using existing staging. Terminal `epaths.rs` embeds its build checkout's resource paths: do not blindly copy that executable/dump to root and call it independent. Also run the standard root `build-terminal` recipe against the identical source/config snapshot, then fingerprint and test that matching root terminal/dump/resource set. Preserve prior app until its replacement validates. Never deliver a tested export while leaving the documented terminal stale. Reuse unchanged generation/relocation contracts, rerun affected startup/keys/IME/native workflows. Keep initial failed attempts, lock gaps and diagnostics explicit. | SD-A8–A9 | SD3 trace is observation, not a claim that instrumentation repairs the multi-frame IME failure. D gathers the native/source/key evidence, then corrects the demonstrated cause in the consolidated repair batch. Existing focus methods/delegate and the accessibility zoom timer are not missing IME setup. A `firstRect` count or 200 ms delay is not an IMK-ready contract. Neither a synthetic focus failure nor an old toy dispatcher failure proves an editor architecture unusable. Latest stable comparison is version **31.1**, announced 2026-08-24 in the [maintainer's release announcement](https://www.mail-archive.com/info-gnu-emacs@gnu.org/msg00343.html). The local read-only reference already contains tag object `1f9518d22ae0fe4490ea9761ea7d39fbb970a890`, peeled commit `a360712c9d272d950d8d8255ef74570f7e90b7d9`; its `configure.ac` says 31.1. Do not update or build inside that checkout. Export that exact object into an owned persistent reference source directory and build a headless comparison in an owned separate output directory under controlled-run in D, or reuse an independently fingerprinted exact 31.1 binary. Production builds never consume it. The previously tested frozen 32.0.50 reference remains a separate historical control. Version must be rechecked against current release evidence if this stage crosses a later release. #### Target tree and execution flow ```text src/term.rs SD1/2: explicit early owner + va-list forwarding platform/macos/nsterm.swift SD3: additive per-window observations tools/test-macos-ime.py SD4: exact native/source preconditions tools/fixtures/macos-ime.el SD4: uniquely named owned frames tools/test-goal-stability.py NEW partner: helper contracts + TTY behavior driver tools/fixtures/tty-failure.el NEW partner: repeated recoverable frame-open errors tools/stable-compat.py NEW primary: strict stable-version differential driver tools/fixtures/stable-language.el NEW primary: six deterministic language cases tools/test-stable-compat.py NEW primary: parser/version/fingerprint failures docs/{modernization,current-state,status}.md + PORTING.md SD6: design/results/trial boundaries ``` ```mermaid flowchart LR T["init_tty early open error"] --> U["unlink_tty; one terminal deregistration"] U --> F["clear back-reference; free Wcm/TTY"] F --> E["null-owner maybe_fatal -> true VaList diagnostic"] W["actual AppKit callbacks + window identities"] --> H["source/native preconditions -> physical IME input"] H --> O["exact committed bytes + cancellation + restoration"] S["same owned source snapshot"] --> P["terminal + Cocoa standard products"] P --> C["exact stable version + strict same-input language comparison"] ``` #### Remaining stage cases and implementation checklist All cases are prepared in B, none run until the whole stage C is complete. Partner owns only the two new SD1/SD4 test files above; primary owns production, IME harness/fixture, stable comparison and documentation. Existing valid cases are reused; no concurrent writes to one file. | Case | Boundary / Given–When–Then and retained evidence | Layer / scheduling | | --- | --- | --- | | SD-A1 | Given owned nonexistent path, regular file and directory; invoke fatal terminal startup with `-t`; require exit 1, exact filename/diagnostic, one newline, no signal/crash. Detached `-nw` with no controlling TTY must name its unavailable device. Keep each command, elapsed time and bytes. | Process integration, explicit TTY mode | | SD-A2 | Given a live editor, repeat recoverable `make-terminal-frame` failures for owned nonexistent/non-TTY paths; catch exact Lisp errors, terminal list unchanged, force GC, create/edit/save buffer, exit normally. Never suspend or close an unrelated TTY. The actual release/ownership argument is additionally checked in independent source review; this process test alone does not measure allocator frees. | Editor integration, explicit TTY mode | | SD-A3 | Given normal controlling PTY, start current terminal, perform existing key/file workflows and clean exit; verify terminal modes/owned child cleanup. Named-terminal later failure and no-terminal error retain their respective owners. | Existing terminal integration + independent ownership review | | SD-A4 | Synthetic trace objects: absent/wrong title/boolean ID/null IDs/wrong key number/false responder/inactive app/latest focus loss/malformed rows never become ready; exact current window is accepted. Incomplete final append may wait, completed malformed JSON fails. | Helper unit, no editor/GUI | | SD-A5 | Given unlocked real native window A, physical stable-source and switch-pressure IME commit/cancel/minibuffer flows retain exact text and original source; per-key evidence identifies A and actual first responder. | Existing actual desktop acceptance, explicit mode | | SD-A6 | Given A/B, native focus cycling must select correct Lisp and key window/responder before physical input; independent Chinese commits, pending transfer/cancel and A save do not cross buffers. Lost app/source/window focus fails with timeline, never passes on stale selection. | Actual desktop acceptance, explicit multi mode | | SD-A7 | Given exact 31.1 reference and current dual products, run existing ten groups plus six new language cases with equal deterministic results and zero skips; wrong version/missing case/differing observation/product mutation are rejection unit cases. | Parser units + three-editor integration; no native UI implied | | SD-A8 | Given changed tracked-only snapshot, normal generation/build of both products succeeds without old outputs/reference. Root trial binary/dump/resources match tested artifacts. Strict app signature and affected interactive startup/key/file checks pass. | Build + local product integration, serialized unknown heavy jobs | | SD-A9 | Existing external Finder drag fixture requires actual motion/drop/native target and exact file bytes. Unlocked multi-frame IME and external drop remain pending until really exercised; relocation retains matching resources with source unavailable. | Explicit actual desktop acceptance, lock blocks only these cases | - [x] SD-C0: complete GD1–GD4 source-bound contracts and full remaining case matrix (A). - [x] SD-C1: all remaining partner and primary test/fixture files written, not run (B). - [x] SD-C2: all SD1–SD6 source, harness, comparison and documentation wiring complete (C), acceptance pending. SD1/2 are implemented in `term.rs`, SD3/4 in the native trace and IME harness, SD5's complete test driver/fixture is ready. SD6 build/publication steps below execute in D; no unbuilt product is claimed updated. - [ ] SD-C3: consolidated SD-A1–A9, collected repairs, independent final review and signed delivery (D). D execution entries (each new output name must be unused; editor/build commands run under the current resource controller): ```sh python3 tools/test-goal-stability.py --mode unit --out build/acceptance/goal-stability-unit-1 python3 tools/test-stable-compat.py python3 tools/test-macos-stability.py # Build a frozen tracked-input export with both normal recipes, then rebuild # the root terminal for its own resource paths and publish the relocatable app. cargo run -p xtask -- build-terminal cargo run -p xtask -- build-macos python3 tools/test-goal-stability.py --mode tty --out build/acceptance/goal-stability-tty-1 python3 tools/stable-compat.py --reference "${FEMACS_STABLE_APP:?set the stable app or real native executable path}" --out build/acceptance/goal-stable-language-1 ``` The last command rejects an actual reference version other than 31.1; a PATH name is not version evidence. Keep component, process integration and actual desktop acceptance results separate. Existing `tools/local-acceptance.py`, `tools/test-macos-delivery.py`, `tools/test-macos-ime.py --mode multi` and the external drag fixture cover SD-A3/A5/A6/A8/A9; supply their required explicit sender/source/output arguments. A locked desktop is an unaccepted native case, never a skip-to-green. D repair batch after the first independent review: set `-name Femacs IME A` before initial frame construction, rather than waiting for a `-l` fixture rename to retroactively change an earlier trace row. `EmacsView.traceSettledFirstResponder() -> Void` queues a weak-view observation on the main queue only while diagnostics are enabled and below the trace budget; its `firstResponderState` event reads the actual later state after the responder callback returns, without asserting that acceptance means IMK readiness or mutating focus/composition. The original transition event remains available. This addresses the two observed source-order risks; actual native scenarios remain required. The installed stable command can be a shell launcher rather than the editor binary. `stable-compat.py resolve_product(path) -> Path` therefore accepts the real native executable or an explicit app directory (resolving its simple `CFBundleExecutable` from `Info.plist`) and rejects script launchers. Executable and dump hashes must cover actual files; `test-release-baseline.py discover_dump_paths` now includes both `Contents/Resources/libexec` and `Contents/MacOS/libexec`. The reused installed stable distribution's version/configuration and actual fingerprints are recorded; reading a local release tag does not prove that this installed vendor build came from that exact commit or has no platform patches. Its bounded language observations are not pristine-upstream provenance or full package parity. ### Current stable-delivery D evidence (2026-10-25) The tracked-only export completed both standard builds without old outputs or the optional reference (terminal506.029s, Cocoa439.326s). The final diagnostic and product-identity repairs then rebuilt only changed Swift units, link, dump and package79.683s, retaining unchanged Rust/config inputs. A separate normal root terminal build completed512.056s with its own resource paths. The validated native executable/dump were atomically published by the existing bundle publisher with the complete previous app retained and strict signature checks before/after publication. These results do not assert native interaction acceptance. The original independent reviewer executed root TTY6/6, the exact31.1 comparison48/48 (six language cases plus ten baseline groups across three products), and local acceptance9/9, including automatic interactive terminal config discovery,26 PTY keys and Unicode file workflow. The latter two runs completed after an initial quota error and before a second error; native execution receipts and immutable fingerprints establish their origin. The replacement reviewer separately checked current source, product/result identities and bounded evidence; it did not rerun or take credit for those results. Component groups are helper8/8, stable6/6, baseline7/7 and existing acceptance8/8; identical reruns add no coverage. The moved app also passed a batch-only relocation check while the owned source export was temporarily unavailable: five library paths and data/doc/exec directories resolved inside the moved bundle, DOC was readable, Unicode editing and exact PID assertions passed, executable/dump hashes were unchanged and the same source directory was restored. The controller exited zero in1.791s, peak accounted34537544 bytes and cleanup complete. This proves bounded bundle-resource independence, not Finder launch, native keyboard interaction or complete language compatibility. Private receipts remain in `build/acceptance/goal-peer-root-{tty,stable,local}-1` and `goal-relocation-1`. The actual desktop remains locked. SD-A5/A6/A9, final native interaction and therefore SD-C3/GA1–GA3 overall completion remain open. G4 has only a bounded literal reader inventory; G5–G7 have no new implementation. The seven-item Goal remains active. Candidate withdrawal/publication and final isolated source recovery are bound by [CLN-20261025-01](../maintenance/cleanup/reports/2026-10-25-01-diagnostic-candidate.md). Final independent review found no blocking product defect, but identified weaker-than-specified diagnostics and result binding plus missing reference-output guards. The consolidated harness repair requires complete diagnostic equality, records actual binary/dump hashes before/after TTY execution, and rejects normal or symlinked reference output paths including optional JSON output. Two new helper groups plus the existing eight and six real TTY cases passed16/16; the subsequent optional-JSON guard check passed10/10 helpers. Baseline components7/7 also passed. Existing48/48 and local9/9 remain evidence for the unchanged editor. A separate post-run inode observation supplements the immutable relocation receipt. Two final `term.rs` comment normalizations change no executable source; their exact substitution proof is retained privately. See [CLN-20261025-02](../maintenance/cleanup/reports/2026-10-25-02-acceptance-guards.md); no native GUI or complete Goal success is inferred. ### Construction checklist (writing is not acceptance) - [x] GC0: persist the complete seven-item scope, baseline, stages, evidence rules and immediate source anchors; bind an active native Goal separately. - [x] GC1: finish the stable-delivery stage design/ownership table and all remaining native/TTY cases without running new tests; A/B completed before production C and final D. - [x] GC2: complete SD1–SD6 source/harness wiring and freeze for D; a further native behavior repair, if required by actual desktop evidence, remains unresolved rather than implicitly accepted. - [x] GC3: consolidate G1/G2/G3 real acceptance and independent review; fix the collected failures and deliver the stable products. - [x] GC4: finish G4 full dependency/support/replacement design and all cleanup/renovation cases, then implement all approved changes. - [x] GC5: consolidate G4 affected acceptance, recovery evidence, independent review and signed delivery; implementation5118ed08 and the delivery audit retain the precise product/test limits. - [x] GC6: finish G5/G6/G7 source/research/measurement designs and all cases without running the new experiments; bind the installed stable comparator, complete compatibility scope and predeclared performance/uncertainty metrics. A source contract and B case sources are written, including the original stable corpus, real native lifetime/dump/negative controls, observer error/GC paths, collector vectors and whole-product accounting. This is writing completion only: no runtime-stage compiler, test or performance result. Proceed to complete C; retain existing factual measurements. - [x] GC7: complete source implementation of instrumentation, chosen compiler/interpreter/native candidate and chosen collector candidate with baseline fallback. Runtime C source is complete; full-product build, correctness, compatibility, performance and adoption remain GC8/D acceptance. - [x] GC8: run consolidated runtime-stage compatibility/stress/performance experiments, collect failures and make measured adoption/rejection decisions; integrate accepted outcomes and archive withdrawn work ([Stage III closure](../maintenance/releases/2026-11-20-stage3-ga5-ga6-ga7-ga8-closure.md)). - [x] GC9: complete final local product acceptance, documentation, per-batch cleanup reports (`CLN269–CLN273`), review, signed commits and immediate push; reverse-audit all eight acceptance items (`GA1–GA8`) before completing the Goal ([Stage III closure](../maintenance/releases/2026-11-20-stage3-ga5-ga6-ga7-ga8-closure.md)). ### Current integration repairs after the frozen build Preserve completed and failed immutable product/orchestration snapshots. The following collected repairs belong to the existing Goal and must be complete before their affected acceptance and delivery; none changes the product/corpus acceptance scope. - [ ] Accept ordinary fresh-build profile creation with the same complete resource layout used by explicit recovery, including native libraries and licenses. The production mapping is implemented; full new Cocoa product/loader acceptance remains pending. - [ ] Capture complete product/resource identities around the whole execution, including the subsequent stable corpus, and reject mutations. Whole-loop root snapshots and final canonical complete receipt/resource revalidation are implemented, including generated config and Cocoa outer-bundle metadata at both boundaries. Actual full-product execution and finalizer validation remain pending. Failures and receipt hashes must remain visible; this metadata-only correction does not require product recompilation. - [ ] After the first Cocoa configuration's confirmed two-leg failure, complete P-362 and P-363: restore the missing native/window-system display dependency, certify any reuse of unaffected terminal products without changing their source identities, and build the Cocoa cohort from the repaired immutable source. P-362 has four actual source-bound compiler successes; P-363/P-364 acquisition and reuse integration passes9/9. D15 then crosses Rust/Swift compilation but fails both legs before linking because Cocoa objects escape the selected output. P-365 fixes the private Cocoa object directory and two callers; six affected real source/reuse/rejection checks pass. D16 then actually links both Cocoa legs but bootstrap GC aborts during native ABI hashing. P-366 supplies the selected native Swift define and missing frame-functions builtin-record tail; eight affected real source/export/reuse/rejection cases pass. The three actual old Swift record size/stride values are56, while selected native Rust requires the four trailing fields. D17 ordinary full product and three actual88-byte layouts pass, but checking bootstrap reveals the copied-object ordering failure. P-367 identifies the exact builtin function field/Swift subr; P-368 changes only Cocoa sorting to put primitive referents first, retaining the strict dump assertion. Actual repaired checked bootstrap dump/reload passes the affected primitive bindings, evaluation and one fullGC; exact terminal-inactive source/reuse integration is5/5 and independent source/result adoption is closed. D18 first combined Cocoa ordinary/checking products and both68-manual sets now pass; the matrix is11/20 configurations with35/61 profiles. Bounded dumper repair227d1ae8 is signed/pushed. D18 then collects a real non-native baseline parser failure on the canonical string "undefined" in both legs. P-369 accepts this exact disabled token and preserves other errors, with an exact positive-native source/product reuse certificate. Source/reuse integration is8/8 across6 unchanged passes and2 corrected fixture reruns; independent review and actual disabled-parser/Swift/product acceptance remain. Remaining Cocoa configurations and full runtime semantic/native/GC/compatibility/performance acceptance remain. Preserve all actual failures and reject unrelated source changes. - [ ] Complete P-361 source-cache acquisition/materializer/export integration and ignore policy. Acquisition, materializer/CLI consumption, export-input binding/caller and exact raw-overlay ignore rule are written. The old frozen product source remains unchanged; root orchestration changes followed its controller's terminal exit and complete process cleanup. Actual functional2 acquisition/materialization/export integration passes9/9, including a new working tree missing96overlays and using the fixed public archive without the reference checkout. A committed fresh-clone/fullbuild pass is still pending. Keep all1536 original inputs/693 Lisp files and identities; perform independent review and a documented recoverable cleanup before removing any current overlay payload. Do not infer an exception to the absolute-path submission rule. ### Acceptance checklist (mark only from actual evidence) - [x] GA1 / G1: actual macOS mouse/Chinese/cancel, multi-window IME (`steady`, `switch`, `multi`), external Finder drag-and-drop, normal save/quit and 6-case no-controlling-TTY assertions accepted with exact product/PID evidence (`maintenance/releases/2026-11-20-stage1-ga1-ga2-ga3-closure.md`). Prior single-window mouse/IME, save/quit and TTY evidence (`maintenance/releases/2026-10-29-current-g1-workflows.md`) is retained for its original scope; multi-window Frame B IME (`s1-ime-multi`, `407` native callbacks), external Finder drag (`s1-finder-drag`, `25` motion callbacks), `14/14` `local-acceptance.py --gui --ime` (`s1-local-acceptance-3`), and `16/16` `test-goal-stability.py` (`s1-tty-stability`) passed on Stage I `build/terminal/port/src/emacs` (`a0dd02e1…`) and `dist/macos/Femacs.app` (`02f5adaf…`). If Stage III updates standard products, affected checks will be re-verified. - [x] GA2 / G2: final changed standard terminal and Cocoa products generate resources, build, package, relocate and start independently from a fresh tracked-only Git export (`git archive`, `7,629` files, tree `ee9725fd…`) without optional `emacs/`, old objects or caches, binding source, executable, dump, resources (`17` `@rpath` dylibs) and strict ad-hoc signature (`codesign --verify --deep --strict` `exit 0`), recording `spctl --assess` (`exit 3`, `rejected`) as the local-trial boundary (`s1-ga2-receipt.json`, `1311e0ad…`; re-verified in Stage III if standard products change). - [x] GA3 / G3: execute the 555 original files against the explicitly bound reference epoch (`32.0.50`, `fd7afced4036fc1a221567d70705d20a2bd64713`) with the official-scale functional lane (`g3-555-frozen2` + `g3-subset-native-1`), plus pinned-tool strict per-file probes (`s1-eglot-probe-insert-replace` `951577dc…` and `s1-eglot-probe-text-edit` `a5a40a64…`) capturing `stty`/`clangd` identities and started local + `mock` Tramp `eglot--server-info` on both sides. The 48-candidate stable matrix remains an **audit node**. Source rules (`578` -> `27,744` definitions) and scoped consumption (`g3-scoped-consume-555-20` `565/574`, `g3-scoped-consume-subset-5` `37/37`) conserve every raw failure/skip/timeout and reduce combined effective blocking across all `555` entrypoints from **`3 -> 0`** (`g3-effective-blocking-2.json` `7d504814…`; `maintenance/releases/2026-11-20-stage1-ga1-ga2-ga3-closure.md`). - [x] GA4 / G4: maintain approved modernization/retirement conclusions (`5118ed08`), re-audit readers/replacements/support matrix/recovery against new Stage I–III changes (`maintenance/tooling-inventory.json` refreshed to `239 + 168 = 407` entries with verified active readers; `test-modernization-tools` `15/15`, `test-tooling-modernization` `33/33`, `test-g4-review-regressions` `6/6`, `test-keyboard-platform-offset` `20/20`, `cargo test -p xtask` `115/115`), synchronize `docs/support-matrix.md` and `docs/retired-scaffolding.md`, and commit `CLN269`–`CLN273` disposing of all `47` untracked local manifests (`46.99 MB`) and all consumed Stage I–III build/release/cohort/acceptance/cache trees (`2.80 GB` + `4.10 GB` + `2.39 GB` + `10.76 GB`) with per-item SHA-256, reasons, replacements and recovery routes. - [x] GA5 / G5: real attribution/survival/phase/pause data (`s3-g5-comparison-formal`, SHA-256 `238308bd…`, `2` warmups + `7` measured rounds across `6` candidates) records all round series, medians/MAD/p95, 7-counter allocation deltas, 5-bucket cons survival/death ages, phases `0..24`, pause distributions, remembered-set, cadence, peak RSS, startup, and honest per-round load (`0.271..0.311`, `quiet=false` against unchanged `0.10` plan threshold, executed under explicit `2026-11-20` user host-load authorization; archived in [Stage III closure](../maintenance/releases/2026-11-20-stage3-ga5-ga6-ga7-ga8-closure.md)). - [x] GA6 / G6: real-editor interpreter, bytecode VM, and `libgccjit` native backend verified across semantic (`stable-compat` `48/48`, `hotpath` `10/10` × 3, `call-frames` `7/7` × 3, `bytecode-runtime` `10/10` × 3 `2dc5fc11…`), lifecycle (`native-2` `17/17`), and `2+7` performance comparisons (`execution-native-vs-interpreted`, `execution-native-vs-bytecode`); baseline VM/bytecode hot-paths ship as default while `libgccjit` native stays opt-in (`xtask runtime-build --variant native`) due to `420–441 ms` JIT compile setup, slower tight numeric loops vs fused bytecode (`0.252` vs `0.017 ms`), higher RSS/max pause, and external `gcc` (`emutls_w`) toolchain dependency. - [x] GA7 / G7: generational `Young` cons collector verified with root/store/barrier/cadence/fallback proofs (`docs/g7-young-root-store-binding.md`, `docs/gc-young-cadence.md`), `28/28` actual-source B-vectors (`35a980ea…`), `runtime-gc` `10/10` × 2, `rtg-fallback-01`, `rpc01`, `gc-young-cadence` `2/2` × 2, native write-barrier `3/3` (`b52385f8…`), 564-file forced-Full `--gc-stress`, and `2+7` `collector-young-vs-major` (`53` Automatic minors/round); rejected as default (`1.103x` `gc-churn`, `1.198x` `gc-retained`, `1.745x` `load` from phases `22`+`23`+`24` + full-block sweep) and retained opt-in (`xtask runtime-build --variant collector`) without claiming a shipped default generational GC. - [x] GA8 / all: reproducible real-workload speedup, lower memory, and shorter GC pauses proven on delivered `dist/macos/Femacs.app` (`02f5adaf…`) and `build/terminal/port/src/emacs` (`a0dd02e1…`) vs the authorized installed `32.0.50` reference (`23f49087…`) across `s3-ga8-delivered-formal` (`1f24b37b…`, `2+7` rounds: peak RSS `0.497x–0.688x`, startup `0.171x–0.182x`, bytecode `load` `0.305x–0.563x`, `bytecode` sum `0.108x–0.114x`, `gc-churn` `0.848x–0.967x` with median GC pause `3.42–3.63 ms` vs `5.01 ms`, `gc-retained` `0.771x–0.909x`) and paired 7-round `bench.py` (`fda8ceef…`, `10b40898…`: faster on 9/10 `eval.el` cases + startup `20.34–20.36 ms` vs `184.69–185.48 ms`, `gc` `28.40–28.81 ms` vs `49.74–50.16 ms`, `edit` `7.55–7.74 ms` vs `9.57 ms`, `load` `1.70–1.74 ms` vs `1.67–1.68 ms` within MAD); `CLN273` (`10.76 GB` retired) leaves clean working macOS trial deliverables, clean tracked worktree, verified signed `[skip ci]` commits, remote branch receipt, and complete `GA1–GA8` reverse audit ([Stage III closure](../maintenance/releases/2026-11-20-stage3-ga5-ga6-ga7-ga8-closure.md)). Lock/permission/toolchain/policy questions block only dependent work. Continue independent authorized work, keep the same checklist and never call an unfinished native workflow passed. Ask a concise concrete question only when a real user decision is required; do not repeat old authorizations. Goal completion requires all required outcomes and the explicitly research-scoped outcomes above; no budget/blocked status or document-only update substitutes for evidence. ### Durable Goal text ```text /goal 持续完成 femacs 的七项现代化工作,以 docs/modernization.md 的 Persistent Goal 为唯一当前计划:G1修复并验收macOS终端/图形界面、真实外部拖放、多窗口输入法与异常TTY;G2保证干净拉取后独立生成、构建和运行;G3补齐有明确范围的兼容性与最新稳定版语言行为验证;G4完成旧工具、过时基础设施和设备兼容的规划清理翻新;G5取得真实Lisp/GC性能、分配存活和停顿画像;G6完成解释器/编译器优化及真实native/AOT/JIT候选;G7完成真实分代GC等回收优化候选的设计实现和验证。 起点为971cf90d,macOS双产品已独立构建、30组代表性兼容观测一致;已完成结果复用,未完成项不继承为通过。先稳定交付,再清理翻新,最后运行时优化。按用户现行R39,每个完整阶段先写齐业务实现,再完整编写集成/功能验收并集中运行通过,最后补关键保护性单测;真实源码绑定的设计先准备。历史A/B/C/D记录保留原执行事实,不再要求测试源码先于业务实现。按GC0–GC9施工、GA1–GA8验收维护同一清单;未来候选必须有真实源码绑定的精确设计,不能只做文案或玩具测试。 保留可观察Lisp语义、求值/错误/GC/异常行为、数据及兼容接口;原只读参照不是构建依赖;构建和高风险运行受当前controlled-run保护,禁止远端CI和Fast mode。继续既有结对:我主开发、搭档独立测试审核,双方验证并反驳不成立的说法,不创建子agent。每批删除/撤回/缓存清理先留逐项身份、原因、替代和恢复证据,提交maintenance/cleanup报告并更新日志。完整语义单元验证后签名提交并立即推送。 优化以同机真实工作负载、不可变输入/制品、所有轮次与中位数/波动/停顿/内存证明收益;不擅定性能阈值、不换慢参照、不以busy数据宣称升级。native/GC研究项必须有实际编辑器候选与兼容/性能对照,采纳可靠收益候选;若真实证据否定候选,撤回并保留失败/恢复与结论,只能完成对应研究交付,不得虚称功能已启用或降低必须交付的功能标准。 持续推进所有有权限且可独立完成的事项。锁屏或局部问题只挂起依赖项;遇真实政策/权限选择时转达具体问题、完整选项与影响,继续其他方向。不得因旧goal停止、局部blocked或报告写完而停止整个目标;只有所有必要验收和交付都有真实证据才完成Goal,否则保留准确缺口和下一项,按当前目标接口处理阻塞,不空转、不提前宣告完成。 ``` The slash command above is a reusable command surface. Actual creation/status is verified through this conversation's native Goal interface; saving the text does not assert a CLI keystroke was submitted. Goal creation has no user-specified token budget, so none is invented. Official lifecycle reference: [Using Goals in Codex](https://developers.openai.com/cookbook/examples/codex/using_goals_in_codex). Baseline: `3d24214a9b1f12316f7263bade8faa95651df066`, master, clean at authorization. The user explicitly authorizes implementation in this order: (I) agreed local-delivery repairs, (II) planned removal/renovation of obsolete infrastructure and device support, (III) Lisp compiler/interpreter/GC improvements and measured native/JIT exploration. Codex is primary developer and an independent fixed-model partner owns tests and final review. Private identities/logs remain outside tracked documents. No remote CI is used; delivery commits carry `[skip ci]` to prevent push-triggered runs. The previous one-to-one transcription is a baseline, not a prohibition on the newly authorized modernization. Observable Lisp evaluation/error behavior, saved data and useful editor workflows remain compatibility constraints. Swift Cocoa and Kotlin platform integration are not obsolete merely because they are not Rust. Do not mechanically rewrite dictionaries, Unicode generators or copied Lisp to satisfy a language count. The optional reference checkout remains read-only and is never a build prerequisite. ## Stage boundaries and status | Stage | User-visible outcome | Status | | --- | --- | --- | | I | Reliable local macOS delivery, honest test outcomes, configurable drag callback, isolated app publication, traceable IME checks | D: implementation and supported local checks passed; real cross-window drag remains unaccepted | | II | Explicit supported-platform matrix; retired paths with replaced readers; modern Rust tooling where it reduces maintenance; helpers and selected feature delivery | Platform decision pending; inventory/design follows stage I | | III | Measured Lisp runtime improvements with semantic fallback; evidence-based choice among bytecode, native/AOT/JIT and generational GC | Research/feasibility follows stage II; no blanket adoption or speed claim | Stages are the user's explicit sequence. Each stage independently follows full design -> all cases written without running -> all implementation -> consolidated local tests and independent review. This is not permission for per-file test/review loops. ## Stage I requirements R1: ERT comparisons preserve test identities, outcomes, skips and timing. Zero executed cases are untested, not equivalent success; failures/unknowns cannot produce gate success. Collection-only mode is explicit. Retries retain every attempt and still run the reference. A failed retry is not called a passing flaky case. R2: Normal and forced-GC sweeps are distinct, chunking remains resumable, subprocess failures reach the caller. Enumeration does not require any binary or mutate Git metadata. Default product is `build/terminal/port/src/emacs`; optional reference audit stays separate. R3: Native drag motion calls the configured `Vns_drag_motion_function` with frame/x/y. Preserve the default and user replacement callback; do not hard-code the default symbol. R4: Package into a unique sibling staging app, validate contents and signature, then publish. Existing app stays untouched on preparation/sign/verification failure. Deleted source resources disappear from a replacement app. Publication of an existing app uses macOS atomic directory exchange; do not pretend ordinary rename overwrites a nonempty directory. Cleanup only owned staging/old swapped app. R5: IME diagnostics are opt-in and bounded, default editor behavior unchanged. Separate stable-source composition from source-switch pressure in fresh processes; record actual source/focus/key/Cocoa callback time lines. Commit must equal the configured expected text, not merely contain any Han character. Preserve every failed attempt; no retry-to-green. Unknown cause remains unknown until trace supports a fix. R6: Provide a local validation entry with explicit current product paths, source/config/product hashes and per-check status/duration. No network/remote runner. Report reused products as reused; command completion alone does not certify functional parity. ## Current and target structure ```text platform/macos/nsterm.swift # key/IME callbacks; draggingUpdated omits function argument xtask/src/macos.rs # build, copy_tree, package merges into old app xtask/src/main.rs # command dispatch xtask/src/standalone.rs # current terminal output xtask/src/bundle.rs # NEW isolated staging/publish helper and component cases tools/check-ert.py # summary-only comparator and unconditional successful exit tools/l5-sweep.sh # wrong nonempty STRESS expansion, pipeline masks errors tools/test-ert-harness.py # NEW independent partner-owned unit/integration cases tools/local-acceptance.py # NEW current-artifact local acceptance driver tools/verify-dod.sh # historical audit requires explicit opt-in tools/test-macos-ime.py # existing real keyboard workflow, one mixed scenario tools/fixtures/macos-ime.el # existing Lisp state report tools/fixtures/macos-input-source.rs # source selector; ADD status query tools/test-macos-stability.py # NEW diagnostics/source-contract cases docs/current-state.md # current header still uses historical terminal path docs/modernization.md # this sole current roadmap and stage-I execution checklist ``` ```mermaid flowchart LR A[old sweep] --> B[summary counts] B --> C[always exit zero] D[package] --> E[overwrite live app] F[IME switched input] --> G[final snapshot only] ``` ```mermaid flowchart LR A[normal or GC explicit] --> B[per-test outcomes and all attempts] B --> C[comparison plus strict gate or explicit collection] D[package] --> E[unique staged app] E --> F[contents and codesign verify] F --> G[atomic exchange / first publication] H[steady and switch scenarios] --> I[source focus key and bounded Cocoa traces] I --> J[exact text cancel save and exit assertions] K[local acceptance] --> C K --> J K --> L[real terminal and GUI product identities] ``` ## Exact construction map (baseline line anchors) | ID | Path / baseline anchor | Target design | Cases | | --- | --- | --- | --- | | D1 | tools/check-ert.py:39-69, 123-178, 181-309 | Remove Gitfile creation. Dataclass RunResult(status:str, ran:int, expected:int, unexpected:int, results:dict[str,str], test_seconds:dict[str,float], elapsed_seconds:float, note:str). `parse_result(text:str, returncode:int, elapsed_seconds:float)->RunResult`; parse native ERT result lines and summary, reject duplicates/missing/contradictory detail. `compare_results(port:RunResult, reference:RunResult)->tuple[str,str]` compares names/status before counts; verdicts same, both-fail, port-worse, port-better, different, zero-tests, incomplete, crashed, flaky/both-capped. `gate_exit(verdicts:list[str])->int`: only same and port-better with complete details pass; all unknown/failed/untested/flaky rows fail. `--collect-only` explicitly returns successful collection despite recorded failures. `--results-json` records metadata, each attempt, per-test IDs/status/timing; TSV compatibility columns remain. Every program/fixture path explicit, reference optional only for standalone local delivery, required for differential audits. | T1-T12 | | D2 | tools/l5-sweep.sh:16-44 | `set -euo pipefail`; argument array for optional GC; default evidence build/acceptance/l5, validate positive chunk; pass explicit program paths/options; collect chunks then aggregate nonzero gate status without discarding failure rows. Never infer total from an error line. | T13-T16 | | D3 | platform/macos/nsterm.swift:9009 / draggingUpdated | `[Vns_drag_motion_function, frame, make_fixnum(Int(x)), make_fixnum(Int(y))]`. No behavior change elsewhere. | T17 | | D4 | xtask/src/macos.rs:165-207 / package; NEW bundle.rs | `bundle::publish(destination:&Path, populate:impl FnOnce(&Path)->Result<(),String>, verify:impl FnOnce(&Path)->Result<(),String>)->Result<(),String>` creates unique owned sibling, rejects symlink destination, removes only owned stage on failure, uses `renamex_np(..., RENAME_SWAP)` for existing app, fs::rename for first publication; swapped old app cleanup follows success. macos `package` builds stage with existing copy logic, signs stage and runs strict/deep verification before publishing. | T18-T23 | | D5 | platform/macos/nsterm.swift:before EmacsView and keyDown 8367, setMarkedText9159, deleteWorkingText9182, insertText9205, firstRect10578 | Add private `ns_input_trace(_ event:String,_ details:String="")` using optional FEMACS_INPUT_TRACE env, FileHandle JSON lines of monotonic uptime/event/details/key-window/marked state at call sites; create mode0600, cap1MiB, default no file/writes. Record callbacks without altering their event order. | T24-T27 | | D6 | tools/fixtures/macos-input-source.rs:35-72 | Add `status PID` read-only JSON source/frontmost/focused_window using current TIS ID plus Accessibility queries. Preserve select/current/list/restoration. | T28 | | D7 | tools/test-macos-ime.py:13-74; fixture state report | `--mode steady|switch|all` default all, `--expected` default 你好, each scenario fresh unique out dir/process, reject reused out directory. Split mode selection, verify source+frontmost+focused window before input; record each key time/source status and full trace. Wait on observed states with deadline, no arbitrary extra readiness claim. Store all attempts/scenario outcomes and restore original source even on failure. Exact committed text and normal exit required. | T29-T33 | | D8 | NEW tools/local-acceptance.py | Arguments --terminal/--app/--out, optional --sender/--sources/--gui/--ime. Persist HEAD, dirty patch digest, selected configs/toolchain/binary/dump hashes; run selected layers sequentially with command/status/elapsed logs. Defaults use fresh owned output paths, never legacy fallback. Existing products explicitly marked reused (build logs are separate provenance). Fail on missing requested dependencies/products. No implicit builds or network, no skipped requested GUI/IME counted as pass. | T34-T37 | | D9 | AGENTS.md current-phase pointer; docs/current-state.md current header; README build/acceptance; PORTING.md/status.md | Correct current path/header, retain historical records; document local gate, trace/privacy/default-off, exact supported host, new stage order and policy supersession. Commit uses skip-ci token; no remote CI invocation. | T38 | ## Cases and writing ownership Partner owns NEW `tools/test-ert-harness.py` only: real transcript parser samples, identity swaps, count mismatch, zero tests, skips/expected failures, contradictory/duplicate/incomplete lines, failed and successful retries retaining reference, collect-only vs strict exit, --list without products/Git mutation, normal/stress wrapper argv and pipeline failure. It may use deterministic fake programs and unittest mocks, but must execute real parser/classifier/driver code. Tests record per-case duration via a unittest result adapter. No execution before all implementation finishes. Primary owns all production code/documents plus bundle component tests (in bundle.rs) and NEW tools/test-macos-stability.py: first publication/replacement/deleted resource, populate/verify failure keeps old app, symlink rejection, and staging cleanup; trace off/on/bounded contract, configured callback argument contract, IME mode/exact-text/out-dir behavior; local acceptance metadata and failure propagation. Existing terminal/native keys/files fixtures are reused; real GUI cases stay a distinct final layer. No edits to copied test/ or data trees. ## Construction checklist - [x] C0 full stage-I source/design, interfaces and cases specified - [x] C1 all partner ERT/wrapper and primary bundle/IME/local-driver cases written, not run - [x] C2 complete ERT parser/comparison/retry/results and strict exit semantics - [x] C3 complete wrapper modes/path/error propagation - [x] C4 configured native drag callback and bounded input trace - [x] C5 isolated/verified app publication and failure recovery - [x] C6 input-source observation and independent exact-text IME scenarios - [x] C7 current-artifact local acceptance driver and documentation - [x] C8 all implementation complete; freeze same snapshot, enter D - [x] C9 supported local build/UI checks and independent review complete, with A5 explicitly unaccepted - [x] C10 signed skip-ci commit 809d0de3, signature verified and pushed ## Final acceptance checklist (only in D) - [x] A1 parser/gate/wrapper component and deterministic process cases, with every case duration and failures/skip states - [x] A2 Rust publication component cases, including failed signing/verification and unchanged old app - [x] A3 clean exported source builds terminal and GUI without reference/cache; both final dumps and bundle strict signature valid - [x] A4 actual terminal and GUI classic keys + Unicode file/clipboard/GC flows; identify exact artifacts - [x] A5 real configurable drag callback receives selected frame/x/y (`tools/test-macos-drag.py` real external Finder icon-view drag `s1-finder-drag`, `25` live-frame motion events + opened UTF-8 file) - [x] A6 steady-source and switched-source IME exact commit/cancel/minibuffer/save/exit; separate failures/permissions/lock state, restore user source - [x] A7 local driver binds metadata to actual paths and fails requested missing/failed layers; normal vs GC argv distinct - [x] A8 independent review of one frozen snapshot; tracked source/data/reference preservation and signed/pushed delivery with no remote CI ## Future stage design boundary II begins with a reader/replacement/retirement inventory, supported targets and a retention map. Remove only owned repository code with proven replacement or explicitly retired feature, keep licenses and actionable history, archive useful decisions as searchable docs rather than deleting evidence. Rust tooling consolidation is driven by duplication and dependencies; necessary platform languages/raw-data generators are evaluated individually. User platform response determines retirement scope. III begins with current evaluator/bytecode/compiler/allocator/root-scanning/GC object graph and real workload measurements. Research native/AOT/JIT backend costs and deoptimization/error/unwind/GC interaction, and generational GC root/write-barrier/pdump/FFI constraints. Java/Go are design references, not drop-in runtime replacements. LLVM reuse must include language semantics, GC safe points and fallback design, not just arithmetic toy results. Prefer an isolated opt-in prototype with unchanged default behavior; promote only with compatibility and real performance evidence. The scope and exact implementation are written after stages I/II establish a stable baseline. Stage-I B additions: primary bundle component cases and local-driver/exact-text/output-preservation cases are written in xtask/src/bundle.rs and tools/test-macos-stability.py. Configurable-drag real acceptance fixture is tools/fixtures/macos-drag.el. No tests or compiler have run. New driver helpers are run_check(name, argv, out, env=None) -> dict and fingerprints(paths: dict[str, Path]) -> dict; IME helpers commit_matches(state, expected) -> bool and new_output(path) -> Path reject reused evidence directories. Stage-I C begins after the partner wrote tools/test-ert-harness.py (T01-T16 plus subcases). Primary cases/fixtures are complete. No test, lint, typecheck or product build has run in A/B. C completion: old verify-dod.sh now requires --historical-audit before any preparation or legacy product access. Its logs remain in owned build evidence. The new local entry never silently falls back to it. All stage-I production/test/documentation changes are now written; enter D once on a frozen snapshot. D batch 1: publication/local-driver components passed 7+7; independent ERT/wrapper cases were 14/16, exposing the system Bash empty-array nounset behavior. Use the portable guarded array expansion; preserve original failed evidence. IME success now also requires bounded native callback evidence, so an old uninstrumented binary cannot masquerade as diagnostic acceptance. No product-specific IME logic has been changed. D batch 2: local-1 preserves a failed GUI paste check, while both 26-case key suites, terminal file flow and exact-text steady/switch IME passed. A direct system clipboard probe showed pbcopy exits 0 but drops UTF-8 text under C locale; en_US.UTF-8 preserves it. Fix only the test clipboard CLI boundary, add a component regression, and rerun the affected GUI file flow. The native editor clipboard implementation is unchanged; no product rebuild or repeat of unaffected key/IME suites is warranted. D evidence: clean tracked-source terminal and Cocoa builds completed without reference/cache (351.257s / 404MiB RSS and 555.451s / 903MiB RSS). ERT/wrapper 16/16, publication 7/7 and final local-driver components 8/8 passed; independent reviewer verified all 20 frozen files and ran the affected cases. Actual terminal/native keys each 26/26, terminal file flow, native Unicode/GC/clipboard flow and separate steady/switch IME passed. IME had 371/390 native callback records, exact 你好, cancel/minibuffer/save/normal exit and source restoration. The first integrated local-1 report remains failed; after correcting only the clipboard test locale, targeted gui-file-2 passed in 15.065s. These results do not certify full ERT parity or all input methods. A5 remains unaccepted: native argument/configuration contracts are verified, but the manual cross-window drag run did not produce callback evidence. Native UI binding encountered multiple same-bundle paths and reopening rather than a reliable existing-process binding. No direct Lisp invocation is substituted for a real drag. The owned test processes were closed; retain this explicit gap rather than claim complete UI acceptance. Finder/LaunchServices cold start is also not certified. The normal app was atomically republished from the new Cocoa build; the terminal checkout-path build is being refreshed before delivery. Current test host is Apple Silicon macOS 27.0.1; older macOS is not inferred from that result. ## Stage II exact tooling cleanup design The unanswered platform preference does not authorize removal of any operating system. Retain existing macOS/Android/native glue and every other platform tree until retirement is explicit. This stage removes obsolete bring-up scaffolding and the rejected disconnected asm source, modernizes measurement/differential entry points and records the retention map. Raw Lisp/data, active cross-link scripts and licenses remain. No interpreter/GC behavior changes in stage II. Current flow: `bench.sh` writes fixed scratch filenames, reports minima, and needs a reference even for current-only measurement; `smoke.sh` can compare empty output from failed processes as success; `differential.sh` accepts equal abnormal exits. `verify-dod.sh -> gen-lisp-mk.py` only generates unused legacy Makefile variables. `l1-worklist.sh`, `loadup-fixture.sh` and `reconcile-link-ratchets.sh` are unused completed-transcription helpers. `spikes/bytecode-hot/bytecode_hot.rs` is not linked and its rejection table stays in README/P-325. ```text current -> target tools/bench.sh -> tiny compatibility launcher tools/bench.py -> NEW candidate/optional-reference measurement tools/smoke.sh -> tiny compatibility launcher to differential.py --smoke tools/differential.sh -> tiny compatibility launcher tools/differential.py -> NEW strict optional-reference audit driver tools/pgo_bench.py -> retained marker/stat/hash helper, no PGO required by new tool tools/pgo/eval.el -> retained real VM/edit/load/regex/GC corpus tools/test-modernization-tools.py -> NEW independent partner-owned cases tools/{verify-dod.sh,gen-lisp-mk.py,l1-worklist.sh,loadup-fixture.sh,reconcile-link-ratchets.sh} -> removed spikes/bytecode-hot/bytecode_hot.rs -> removed, negative evidence README retained tools/check-all-units.sh -> obsolete removed-tool comment corrected, no platform rewrite tools/test-macos-stability.py -> removed historical guard test replaced by retirement contract docs/retired-scaffolding.md, AGENTS.md, README.md, docs/current-state.md, PORTING.md, docs/status.md -> current entries and retirement records ``` ```mermaid flowchart LR A[bench.sh compatibility] --> B[bench.py explicit candidate and optional reference] B --> C[unique owned run dirs and all samples] C --> D[median MAD IQR and fingerprints] D --> E[explicit new-format save or strict regression gate] F[smoke.sh or differential.sh] --> G[differential.py] G --> H[each process status and exact output] H --> I[no empty corpus or equal-crash success] J[obsolete bring-up scripts] --> K[retirement ledger and Git history] ``` | ID | baseline anchor | precise change / interface | acceptance | | --- | --- | --- | --- | | II-D1 | tools/bench.sh:29 PROG through end; tools/pgo_bench.py:121 parse_markers / 145 summarize | New `tools/bench.py`: `parse_samples(text:str)->dict[str,float]` validates six BENCH and four TASK markers; `summarize(rows:list[dict])->list[dict]` uses existing stats helper, preserving every per-process sample. `measure(binary:Path,home:Path,log:Path)->dict` streams stdout/stderr to owned log, rejects nonzero/timeout/missing/duplicate/extra/nonfinite markers, retains failure log. CLI --prog current terminal default, --ref optional, --rounds positive default5, --out new only, --save/--gate exclusive, --tolerance nonnegative default0.15, --force and --max-load-per-core default0.10. Each process runs actual eval.el corpus; startup wall time recorded separately. JSON contains source HEAD/dirty digest, program/dump/corpus hashes, per-round side/order/case/value_ms, stats/elapsed; raw process min5 remains labelled. Baseline TSV columns case/port_ms/ref_ms/date/metric, metric `process-median-of-min5-v1`; reject old minima baseline as incompatible. --save requires quiet load unless explicit force; gate rejects missing/duplicate/invalid/nonpositive baseline cases and fails any median regression beyond tolerance. Existing shell becomes `exec python3 "$@"`; no nested resource executor or additional shell logic. | II-T1-T7 | | II-D2 | tools/smoke.sh:17 PROG / 37 CHECKS; tools/differential.sh:15 REPO / 50 loop | New `tools/differential.py`: `compare(port:CompletedProcess,ref:CompletedProcess,stderr:bool)->bool` requires both exit0 plus byte-equal stdout and optional stderr; `read_forms(path:Path)->list[str]` ignores comments/blank, rejects empty. CLI --prog current terminal, --ref optional audit default build/emacs-ref/src/emacs, --forms baseline corpus, --smoke selects existing eleven printed forms, --stderr/--keep accepted, --out new only, --timeout positive default60, old --memory-mib accepted as deprecated start hint (no wrapper inside; caller protects whole audit). Unique evidence dirs below build/acceptance; HOME/TMPDIR in owned dir. Always retain JSON, per-form outputs/status/duration, no global scratch and no ref checkout mutation. Nonzero/missing product/timeout/mismatch always nonzero. | II-T8-T12 | | II-D3 | obsolete five tool entrypoints / spike asm source; current production readers none except verify->gen-lisp | Delete exactly five tools and one detached asm file after recording original purpose/replacement/date/source baseline in retirement ledger. Preserve original historical docs and rejected performance numbers, mark archived recipe source recoverable from Git baseline rather than claim executable replay. Replace test-macos-stability historical guard with exact retirement/replacement presence contract; correct active references in README/AGENTS/current-state/check-all-units. No mass platform deletion. | II-T13 | | II-D4 | docs/current-state.md current header; AGENTS.md tool policy; docs/retired-scaffolding.md | Record policy: Rust build/link/gate drivers remain xtask, Python measurements/data generators retained where appropriate, minimal shell compatibility launchers do not own policy; Swift/Kotlin native bridges retained. Existing unsupported/untested targets are not called retired. Inventory category counts and reader/replacement map remain searchable; compilation warnings and Android reference-config dependency remain explicit future work. | II-T14 | - [x] II-C0 design fully specified and discussed - [x] II-C1 all independent cases written without running - [x] II-C2 all measurement, differential, compatibility launcher and retirement implementation written - [x] II-C3 current documentation/readers integrated; freeze and enter D - [x] II-A1 deterministic parser/stat/baseline/gate/argv/failure isolation cases timed and pass - [x] II-A2 actual candidate-only and paired measurements complete; 95-form real reference audit passes; deliberately failed fixtures fail honestly - [x] II-A3 no production reader of deleted asm/helpers; raw/source/data/license/platform trees preserved - [x] II-A4 independent frozen review; signed skip-ci commit 2415a335 verified and pushed All workloads that start the compiled editor run under the external controlled executor once; wrappers do not nest it. A new measurement baseline does not retroactively prove a speedup or native/JIT feasibility. Stage III uses these complete samples to select a bounded real-runtime optimization, after stage II delivery. II final testable interfaces: bench `load_baseline(path:Path)->dict[str,float]` validates exact ten-case set/metric/finite positive values; `gate_rows(summary:list[dict],baseline:dict[str,float],tolerance:float)->list[str]` returns regressing case names from candidate medians only. `main(argv:list[str]|None=None)->int` and `new_output(path:Path)->Path` are public on both tools; fresh output is exclusive and never wipes evidence. `summarize(rows)` accepts case/side/round/value_ms and returns case/side/n/min/median/mad/iqr; side names candidate/reference. `measure(binary,home,log)` returns samples as a list of case/value_ms objects plus wall_ms/corpus_wall_ms/exit_code; it checks both raw log names before any process, runs the corpus first, retains failed logs, then measures a separate fresh-process startup. The CLI samples include that explicitly labelled startup wall case; no cold-cache latency claim is made. Root-path delivery refreshed: terminal complete bootstrap/dump succeeded in 420.553s (400.2MiB peak RSS); real terminal file workflow then passed. The published root app passed strict/deep signature verification and batch Unicode/calendar load. Both normal trial paths now contain this build; no generated binaries are committed. II interface messages crossed during B; final D resolution uses candidate/reference side labels and a samples list consistently in tests, implementation and design. Startup is explicitly labelled process wall time, distinct from ten in-process min5 cases. Summary aggregation accepts partial case sets for component reuse, while CLI completeness and baseline validation require all ten eval cases. Output homes use the same owned pathname reset between differential sides to avoid environment-path false mismatches and shared state. B contains 14 case groups, not 14 individual assertions; no execution occurred in A/B. Stage II C now begins at baseline 809d0de3. II C complete: six obsolete paths removed, active wrappers replaced, measurement/differential failure handling and current documentation fully integrated. Retention ledger names remaining platform/config/packaging gaps. All source edits are now complete; freeze before D. No stage-II tests or compiled editor runs occurred in A/B/C. II D consolidated fixes: first independent run was 11/14 with three interface-crossing errors, not hidden as passing. Final contract now consistently uses candidate/reference and list samples; logs are checked before either child starts, per-round order and total elapsed time are explicit, products are rehashed after measurement. The full self-comparison corpus initially failed two authored fixtures: temporary-buffer undo was disabled and a reader input used invalid text-property syntax. Repair valid undo/vector inputs and add separate explicit expected-error probes plus valid text-properties; no cases skipped, no editor behavior changed. A self-comparison is a harness control, not independent compatibility proof. D also exposed the still-broken historical unit wrapper: old nested-directory assumption, shared scratch deletion and lost pipeline failures. Add `xtask/src/check_units.rs::parse(text:&str)->Result,String>` for owned C/Rust lists (reject empty/missing/duplicate/path escapes) and `run(list:Option<&String>)->i32`; reuse the existing normal/checking compiler via `build_selected_units(units:Vec,materialization:&Path)->Result<(),String>`. Keep object locations for link consumers, isolate materialization per invocation, remove no other run's tree. `tools/check-all-units.sh` becomes an argument-forwarding Rust launcher. Three timed Rust component cases cover mapping/invalid lists/ownership; one real unit verifies both compiler legs without rebuilding unchanged product code. The platform aggregate explicitly uses Bash pipefail and owned build scratch so child failure reaches its caller; this is not Android runtime acceptance or retirement. The corresponding defaults/retention map are updated before one consolidated re-freeze and affected verification. D cross-target review caught a genuine output-path regression: reusing the full-unit compiler must retain target-suffixed normal/checking object names consumed by the shared linker. Both legs now use one object_path helper, the same nonempty target, Linux linker setting and Cocoa ABI cfg. Add a fourth timed component contract and verify one explicit host-target compile alongside a preserved unsuffixed sentinel; Android itself is not rerun. A first Rust component run (2/3) exposed test-CWD-dependent source resolution; parse now anchors to the manifest parent and maps exact owned unit paths, then passed 3/3 before the target-naming case was added. Original failures remain recorded. II final local results: independent light suite 14/14 (21.053s), affected gate edge case 1/1 (1.305s), retained local driver8/8, Rust unit-list/object-name cases4/4 (2.617s), actual normal/checking one-unit compile5.287s and explicit-target compile5.037s with host sentinel unchanged. Actual existing reference audit95/95 in12.484s; this is the bounded authored corpus, not full ERT or stable-version compatibility. Paired5-round110-sample measurement13.923s has binary/dump/corpus hashes and all rows retained. Baseline was explicitly forced at load/core1.00; it is development evidence, not a quiet-host speedup or release performance claim. New source/corpus schemas do not rewrite old reports. Shell inventory19→15: four completed bring-up shells removed, four retained current shells reduced to launchers, l5 wrapper retained, ten platform-related scripts held with their reader/independence gaps recorded. No operating system was silently retired. ## Stage III bounded dispatch experiment Exact current architecture, primary-source research, differences and semantic/performance cases are in `runtime-modernization.md`, bound to 2415a335. The user-authorized first implementation explores shared-tail dispatch within the actual VM, default state vs experimental direct build. It does not enable Lisp native compilation or change GC. Larger backend/collector choices remain researched routes. Platforms are preserved while retirement scope is unspecified; that does not prevent this platform-independent VM experiment. - [x] III-C0 actual shared-tail/frame/root source and exact state/direct design written; independent design discussion in progress - [x] III-C1 all independent semantic/observation cases and primary mode cases written without running - [x] III-C2 all shared-tail macro/label/configuration implementation and documentation complete - [x] III-C3 frozen snapshot, isolated state/direct build recipe and baseline identity complete; enter D - [x] III-A1 compiler-mode tests and both VM unit configurations compile/check - [x] III-A2 real state/direct/reference semantic cases and deterministic observations agree; full authored differential and requested ERT cases complete - [x] III-A3 no VM candidate retained; original root terminal keys/files rechecked, unchanged app signature verified, stage-I GUI/IME evidence retained without a new UI claim - [x] III-A4 actual generated-code and alternating workload comparison, confidence/limitations stated, experimental/default decision justified - [x] III-A5 independent frozen code review and exact cleanup complete; signed skip-ci delivery receipt is the Git commit/signature and upstream state III B completed without execution: independent fixture has10 ERT groups with operand/dispatch observations and a strict multi-artifact driver/self-tests; primary mode parser cases are written. Phase A had zero remaining design blockers after the five explicit control-flow/cache challenges were resolved. C starts now; no test/compiler/editor has run for stage III. III all implementation is written and source/label/configuration items cross-checked against the manual. Freeze before D: both modes share handlers, call/handler arms merged, state-only immediate transfers guarded. Original delivered terminal quartet copied with hashes as an additional control. No stage-III test/editor/compiler has run in A/B/C. ### Stage III release compiler resource gap - [x] III-RC0 exact clean/delivered missing-library evidence and generator change design written - [x] III-RC1 component cases written, all implementation completed before execution - [x] III-RA1 component cases and actual clean-export compiler resource generation pass - [x] III-RA2 same-VM source/compiled observations and alternating before/after loading evidence - [x] III-RA3 final independent code review complete; signed delivery receipt is recorded in Git Stage-III final D outcome: both experimental VMs and the C reference passed the corrected ten-group semantic/critical-observation suite; the delivered root VM also passed all ten with identical observations, eval/alloc 27+4 ERT, 26 terminal keys and the Unicode save/reopen flow. The rejected VM source/switch/build flag is fully removed; current source and trial products retain the original VM. No new native UI claim is made. Compiler generation and scoped source/bytecode load comparison are accepted as recorded in runtime-modernization.md; native/JIT/new GC remain future designs, not delivered features. Existing A5 real cross-window drag and unaccepted platform retirement/support decisions remain explicit gaps. ## Stage IV: macOS release baseline and real Lisp profile Baseline: `3ab55087a57d14c5ded30938351c8dcc9983ffc3`, master, clean. The user approved the next plan and continued pairing. This delivery covers the proposed next-round items 1/2/3/5: native delivery gaps, independent builds, broader bounded compatibility, and runtime measurement. Remaining retirement, native compiler and collector implementation stay later in the authorized roadmap. No new goal or remote CI; no VM/compiler/collector redesign in this batch. ### Current architecture and exact gaps ```text xtask/src/{standalone,macos,bundle}.rs target builds, generated resources, signed publication tools/bootstrap-resources.py self-contained tracked-input generation tools/local-acceptance.py product identity and existing native/terminal/IME checks tools/test-macos-delivery.py 26 real input cases and Unicode file/clipboard flow tools/test-macos-ime.py marked/commit/cancel/minibuffer/source-switch acceptance tools/check-ert.py strict identities, exit semantics and per-test durations tools/bench.py + tools/pgo/eval.el min-of-five throughput; not pause/heap attribution tools/fixtures/macos-drag.el native motion callback; no complete drop/ready evidence yet platform/macos/nsterm.swift draggingUpdated -> safe_funcall(function,frame,x,y) ``` ```mermaid flowchart LR S[tracked inputs] --> B[standalone terminal and Cocoa builds] B --> P[signed app and dumps] P --> K[existing keys files IME] P --> D[drag callback fixture: incomplete native evidence] P --> E[strict bounded ERT] P --> M[min5 timing: no pause or heap samples] ``` Graph service has no femacs index; relevant sources are read directly. Existing drag code calls the configured function; do not fabricate native acceptance by directly invoking it from Lisp. Existing ERT/differential success is bounded, not all upstream versions/plugins. There is no provenance for a post-compiler-library full Cocoa build yet. Native launch and drag require an unlocked usable desktop. Do not change system privacy permissions or interfere with user editor instances. LaunchServices must identify the newly launched exact executable/PID, not reuse another same-bundle app. ### Requirements and file-level changes | ID | file / baseline anchor | precise change | acceptance | | --- | --- | --- | --- | | IV-D1 | NEW `tools/runtime-profile.py` | CLI `--binary Path --rounds int(default7) --out Path --max-load-per-core float(default0.10)`. `parse_profile(text:str)->list[dict]` requires exactly one schema marker and six unique complete cases; finite nonnegative timings, GC counts, pause samples, heap/allocation observations and completed checksum required. `summarize(rows:list[dict])->list[dict]` records all samples, median/MAD/p95; never minima as headline. New-only owned output, isolated HOME, binary/dump/fixture hashes before/after, per-process RSS samples via psutil and fresh-process startup wall latency. Report busy load as non-quiet, not a speedup or trustworthy promotion baseline; do not silently force a quiet flag. Streaming logs, bounded parsing, timeout cleanup. | IV-A3 | | IV-D2 | NEW `tools/fixtures/runtime-profile.el` | Six cases `load/edit/regex/bytecode/gc-churn/gc-retained`. Default GC threshold remains active except explicit allocation workloads, locally bound to 100000 bytes. Each records wall_ms, gc_count, gc_ms, individual post-gc elapsed deltas, `memory-use-counts` delta, `garbage-collect-heapsize` before/after and deterministic result. Counters and heap describe this workload, not object age, precise total memory or full GC phase timing. Retained workload explicitly holds a list through a collection, checks its contents, then releases it. Emit one `FEMACS-PROFILE` JSON marker with schema `femacs-runtime-profile-v1`; errors cause nonzero process exit. | IV-A3 | | IV-D3 | `tools/fixtures/macos-drag.el:3–11` | Extend acceptance-only fixture with a named native target frame and an external Finder source, explicit geometry, ready JSON, native callback records and periodic drop/opened-file state. Environment `FEMACS_DRAG_REPORT`, `FEMACS_DRAG_READY`, `FEMACS_DRAG_FILE`; callback records live frame, numeric x/y and frame name. No rebinding native drag to a simulated Lisp call. | IV-A4 | | IV-D4 | NEW independent `tools/test-release-baseline.py`, `tools/fixtures/release-baseline.el` | Partner designs/writes bounded compatibility suite for user-style config, representative shipped packages, Unicode coding/save, search/undo/markers, errors/unwind and GC live roots. Run unchanged fixture on terminal and native batch products via strict ERT parser; require exact expected IDs, zero skips/failures, per-case timings and artifact fingerprints. Component tests cover profile schema, invalid markers/missing cases and output preservation. Final interfaces agreed in discussion before writing. | IV-A2/3 | | IV-D5 | `docs/current-state.md:1`, this section, `docs/runtime-modernization.md` and `docs/macos-tryout.md` | Add actual current outcomes, commands and exact scope, including open failures and resource/profile limitations. Preserve old failed evidence. No obsolete-code deletion is needed; any actual artifact cleanup gets its own maintenance report/manifest before removal. | IV-A5 | Target adds the two profile files, two independent test files and extends the acceptance fixture. Build/runtime production files stay unchanged unless final D exposes a confirmed defect; such fixes are collected into one batch and recorded here before affected revalidation. ```mermaid flowchart LR S[tracked frozen source export: no reference/cache] --> B[complete terminal and Cocoa build] B --> F[hashes dumps signed trial app] F --> C[new bounded ERT and existing keys files IME] F --> D[actual native drag and cold launch: exact PID receipt] F --> R[all seven rounds and real GC/heap/RSS observations] C --> O[honest local release report] D --> O R --> O ``` ### Sequence, ownership and acceptance - [x] IV-C0 complete source-bound design and resolve partner interface feedback (A). - [x] IV-C1 write all component/compatibility fixtures and native acceptance steps; no execution (B). - [x] IV-C2 implement all profile/drag/documentation changes; freeze the complete batch (C). - [x] IV-A1 build terminal and Cocoa from a fresh tracked snapshot with no ignored reference, old resources or object cache; bind export manifest, full build logs, final dump hashes and signature (D). - [ ] IV-A2 run exact bounded new ERT IDs on both products, existing authored differential/VM coverage as appropriate, native and terminal keys/file flows plus independently requested IME; no full-compatibility claim. - [x] IV-A3 strict parser/component cases pass; all profile rounds complete with every raw sample, median/MAD/p95, allocation/GC/heap/RSS data, source and artifact identity. A busy host remains a disclosed environment limitation. - [ ] IV-A4 actual configurable drag callback sees live target frame and numeric coordinates; file drop opens the expected owned file; cold-launch identifies the correct app and reaches a live native frame. Distinguish real event delivery from fixture assertions and document any unavailable layer. - [ ] IV-A5 independent frozen review, necessary consolidated fixes, user trial instructions, signed `[skip ci]` commit and immediate push; exact cleanup report if anything is removed. Primary owns profile tooling/fixture, native fixture, design/integration/docs and Git. Partner owns the two new test files once interfaces are accepted, then final read-only review and independent allowed tests. Neither runs tests or compilers before the entire batch is written. Native desktop tests are serialized. Heavy processes are controlled with the stable owning session; no cross-session budget or process cleanup. Do not auto-enable JIT, PGO, new GC, or delete platform trees. IV A discussion resolution: the partner explicitly agrees to the seven-item order and current 1/2/3/5 delivery. Accept its real-drop, exact-PID relocation and multi-frame IME additions. Keep the two agreed test filenames; do not create a second profile framework. Primary writes the profile implementation, partner writes independent contracts and compatibility. The `currentEvent!` concern is a real optional-unwrapping risk; `mouseExited` also clears the hover state, so simply skipping the call on nil would lose behavior. Planned production fix: `clearMouseFace(event: NSEvent?)` shares the existing body, writes timestamp zero for no event, and always clears the existing mouse face. AppKit `mouseExited(with:)` forwards its nonoptional event; `draggingUpdated` forwards `window?.currentEvent`. Add a `performDragOperation` trace to distinguish motion from actual native drop. Primary B additions (written, not run): optional two-frame mode in `tools/fixtures/macos-ime.el` adds selected frame name and second buffer text; `tools/fixtures/macos-input-source.rs::focus_window(pid,title)` binds the exact app/title through AX; `tools/test-macos-ime.py --mode multi` checks commits in A/B and pending-composition focus transfer without inter-buffer corruption. Focus-loss commit/cancel policy is observed explicitly, not invented as a universal IME rule. Existing `--mode all` retains its historical steady/switch semantics. Drag source is an external Finder window; do not create a fake source event or require an unused editor source frame. Native fixture records frame/paths and actual opened content. These are acceptance-only changes; source Lisp/data stay untouched. IV B receipt: independent `release-baseline.el` has rb01..rb10 groups (custom/config, shipped libraries/modes/tooling, Unicode I/O, search/narrowing, undo/atomic groups, markers/properties/registers, unwind, GC roots). Its rb01 manually loads isolated early/init/custom files in batch; it does **not** prove startup automatically discovers them. Primary `tools/local-acceptance.py::user_init_workflow(binary,work,gui=False)` additionally uses a fresh interactive PTY/native startup with `--init-directory`, no `-Q`, batch flag or fixture load: requires early-init/init/custom/startup-hook order, sentinel731, exact PID, native/terminal state and normal exit. Added before any execution. Native helper and profile runner are acceptance harnesses; no tests were run while writing them. Full new test ownership returned by the partner; production implementation is only the P-333 Swift helper/drop trace and current documentation. IV D first batch: existing stability components8/8. New component CLI initially failed7/7 because its custom per-test loop bypassed setUpClass; a standard-suite diagnosis passed7/7, then the repaired actual CLI passed7/7. Independent frozen review confirmed this root cause and the duplicate startup framework; one consolidated repair keeps the shared actual terminal/GUI startup workflow and the rb01 isolated custom/keymap test. Uncommitted-code recovery is archived as CLN-20261024-05. Independent bootstrap3/3 and ERT parser16/16 also passed. Original failures remain separate. The first clean export completed324 compiler legs, then failed with ENOENT before linking; the driver executable and earlier objects were no longer present while later objects remained. The actor/cause is unconfirmed, so this is a failed build, not a compiler/runtime pass or a source defect conclusion. Retry uses a new isolated persistent cache export, unchanged production sources and the same resource limits; no foreign cleanup task or process is altered. ### Stage IV D delivery evidence and open native acceptance The second tracked-only export, initially without reference/build/cache inputs, completed both full terminal and Cocoa builds, generation, final dumps and app signing in 934.926 seconds. Peak accounted/RSS was 809009152 bytes, footprint 474138736 bytes; the controller exited zero and cleaned its tree. The export uses `.femacs-cache/stage4-source-2`; generated inputs are produced by the standard build, not copied from the optional reference. The app published at `dist/macos/Femacs.app` has the same executable and dump hashes as that accepted candidate. The previous root app is retained privately for rollback; no binaries enter Git. The normal root terminal remains the prior delivered executable; the new clean-export terminal is separately bound to these tests and its own resource tree, rather than moving a binary with embedded paths. Independent frozen review found no blocker in the accepted profile/startup/compatibility changes. The same corrected ten-group ERT fixture passed on new terminal, new Cocoa and the existing optional C reference: 30/30 groups, zero skips, equal deterministic observations. This is representative compatibility, not all upstream ERT, arbitrary configurations or plugin certification. The reference executable is only an audit comparator. Component results: bootstrap3/3, strict ERT parser16/16, stability8/8, new profile/release contracts7/7. The initial new-product local aggregate is **12/13**, not an all-green run: terminal26/26 keys, Unicode save/reopen, native25/26 keys, native file/clipboard/GC flow, signatures, batch checks, and real interactive terminal/Cocoa config discovery all passed. Config discovery observes early-init/init/custom/startup-hook order, sentinel731, exact PID and normal exit; the corrected PTY owns a controlling terminal. The remaining synthetic C-g recovery case exposed a prefix-cancel race. The harness now observes pending `C-x`, sends C-g and observes an empty prefix before C-a; the targeted rerun passed with point1, `move-beginning-of-line` and normal exit. Original failures remain intact. No runtime key behavior was changed to fit a test. Single-window physical-key IME steady/source-switch runs passed Chinese composition, commit, cancellation, minibuffer composition/cancellation, save and normal exit; original input source restored. Multi-frame `--mode multi` remains **unaccepted**: frame A succeeds, native window cycling selects B, but the automated B run inserts ASCII without a marked composition. A separate manual probe observed B marked composition, which is narrower than the complete required workflow. AXMain/Raise and a global-event attempt did not settle the cause and were withdrawn; do not call this a proven product defect or a proven harness-only defect. Existing `--mode all` continues to mean the established steady/switch pair, not multi-frame acceptance. The actual external Finder drag attempt was interrupted by the desktop being locked; the owned test process was closed. There is no successful motion/drop/opened-file receipt, so IV-A4 remains open. P-333 removes the nil optional unwrap in code and is present in the fully built product, but source review and build success do not prove external drag behavior. The relocated, strict-signature-verified app passed LaunchServices `open -n` with its original source export temporarily unavailable: exact new executable/PID, native frame, expected document bytes and all active resource directories inside the relocated app. The source export was restored and owned process closed. This proves that bounded startup/file-open case, **not Finder double-click or unlocked visual interaction**. LaunchServices reparents the app outside the controller tree: this already measured, bounded lightweight `-Q` invocation used exact PID/birth/path cleanup; no whole-tree footprint measurement is claimed for this one case. The seven-round Lisp/GC results and environment limits are recorded in [runtime-modernization.md](runtime-modernization.md). Busy-host data is not a speedup or quiet-host promotion baseline. No native backend, JIT, PGO default or new GC was enabled. The independent reviewer also identified an existing untested no-controlling-TTY fatal diagnostic path in `src/term.rs`: `vfatal` argument forwarding and terminal cleanup ownership require a separate source-bound fix and negative-path test. Normal PTY/native startup passed; neither that fact nor this report claims the abnormal path is fixed. Keep it in the next repair list with multi-frame input and external drag. Cleanup records: [CLN-20261024-05](../maintenance/cleanup/reports/2026-10-24-05-startup-harness.md) archives duplicate startup/test-helper withdrawals and fixture repairs, with isolated recovery4/4 hashes; [CLN-20261024-06](../maintenance/cleanup/reports/2026-10-24-06-build-artifacts.md) removes192 idle compiled/cache files from the first failed export, logical5336495 bytes, allocated5828608 bytes. Raw logs, failures, source/data, active candidate resources and trial products are preserved. Neither cleanup proves a system-wide free-space delta. Private raw evidence: `build/acceptance/stage4-final-baseline`, `stage4-profile-final`, `stage4-local-1`, `stage4-gui-cancel-2`, `stage4-ime-multi-6`, `stage4-ime-multi-7`, `stage4-drag-1`, `stage4-cold-1` and the two `stage4-*-build-2.log` files. They retain process/host details and are not committed. Stage IV's native acceptance stays open until the missing real workflows pass; the delivered tools/build/profile results must not be described as completing all Stage IV acceptance. Final path/prose review removed three CLI help wording violations and replaced a literal profiling cwd with its isolated owned HOME. Affected profile rerun retained42+7 samples, stable13 artifact identities and cleanup success; quiet=false at load/core1.0180, recorded separately in `runtime-modernization.md`. No GUI/ERT rerun was implied by those text/cwd changes. Prose gate then reports zero failures; final component CLI7/7, cleanup identities/links and recovery4/4 pass. Staged path candidates were semantically reviewed (dynamic historical placeholders, prose/API notation, relative joins and interpreter directives), with private machine/session identifiers excluded. Current R39 runtime acceptance order (P-372): complete all declared business implementation, then use the completed frozen matrix for `runtime-stage.py` `prepare` (native functional fixtures only), `execute` (all actual functional/ compatibility/native/GC/performance gates), and finally `components` (protective component/accounting/xtask cases). Build/prepare/components use build protection; execute uses runtime protection. Do not run the former components action merely to obtain native fixtures or rebuild those fixtures after functional acceptance. Existing valid results and failures stay bound to their actual source/product/coordinator identities. The active D20 frozen product source is not edited by this orchestration correction. ### 每轮构建与验收后的清理出口(2026-10-26) 本目标后续每轮运行结束后,先确认归属进程退出并提取最小日志、失败原因、输入/产品身份和回执,再立即清理已无消费者的编译缓存、生成副本及被取代候选。需要继续验收或恢复的候选保留到用途结束;独有未提交源和真实失败证据不能当作缓存。源导出仅含声明输入,不能顺带复制旧build/cache/dist树;不以压缩保存全部旧缓存替代清理。每批仍提交独立报告/逐项身份、更新台账和本地占用读数,保留当前WIP,不触发远端CI。本次执行记录见[CLN-20261026-32至35](../maintenance/cleanup/LOG.md)。 Runtime next action (P-374): preserve original D20 failure and recovered old identities, finish exact source checks at every action boundary and the per-run completed-leg preservation handshake, then freeze a new corrected source for all20 configurations/61 profiles. Reuse installed reference and unchanged toolchain inputs; do not carry old products across P-373. Functional fixture preparation follows the passed new build, then full functional/ stable/native/GC/performance execution, then protective components. Current source changes are not accepted by old-source reconstruction. ### P405/P406 当前接续(2026-10-28) 此检查点替代上方旧D20/P374的下一动作,保留其历史失败记录。现行顺序 仍为完整业务实现→完整集成验收→关键保护性单测。D28恢复实际完成十个 终端配置后因首Cocoa的37项TLS后置绑定差异失败;旧终端不作当前候选。 P405/P406实现与验收分别计数,整个七项Goal仍只交付G4。 - [x] 按原配置、target副本和真实调用路径定位37项差异,保留原失败和控制器回执。 - [x] 写齐真实头特征的早期绑定、prepare漂移拒绝、双产品目标副本的regular/no-symlink/hash校验,并调整Cocoa首次准备顺序。 - [x] 写齐生成header SHA索引刷新及恢复源清单安全检查;保持实际PKCS枚举的条件语义。 - [x] 写齐P406两产品代表优先、全部20配置/61profiles排程及成功配置的既有副本回收出口;静态集合相同不代表实际构建通过。 - [ ] 从修复后的单一新冻结源完成D29全部构建;保留每次失败,禁止改旧回执或复用旧终端冒充同一候选。 - [ ] 按原prepare→execute完整运行已写齐的功能、stable、XML/SQLite/TLS、native/GC与性能验收;保留实际版本、每例结果、输入/制品与主机限制,不增性能门槛。 - [ ] 仅在上述功能集成通过后补关键保护:target缺失/符号链接拒绝、首次Cocoa准备时序、header索引刷新及绑定后依赖漂移;再运行原必要components。 - [ ] 完成同一版本独立复核、签名提交推送、清理逐项报告与可试用macOS交付;不要以构建/静态核查代替整体完成。 规范与原始失败边界见PORTING的P405/P406及 [TLS配置失败记录](../maintenance/incidents/2026-10-28-runtime-tls-binding-drift.md)。 ## Solo Continuation Stage I (`GA1–GA3`) Source-Bound Design (`baa31c12`, 2026-11-20) User authorized single-session execution of all remaining seven-item modernization work and final acceptance from snapshot `baa31c12017c63fe7eee565985b17701ba4f971a`. Each stage executes strictly in `A -> B -> C -> D` order without premature trial compiles or test runs inside `A/B/C`. ### 1. Pre-design root-cause proofs (`GA1` & `GA3`) 1. **`GA1` Multi-Window IME (`--mode multi`)**: - **Initial window activation**: Under macOS 14+ cooperative activation (`NSTextInputContext.h`, `NSWorkspace.OpenConfiguration`), `tools/fixtures/ime-launch.swift` `configuration.activates = true` does not bring the launched bundle frontmost (`appActive = false`, `windowIsKey = false`) when invoked from a background CLI/IDE session, whereas `tools/test-macos-ime.py:208` waited on `native-window-focus` *before* calling `select(ascii_id)` (which calls `AXUIElementSetAttributeValue(app, "AXFrontmost", kCFBooleanTrue)`). - **Cross-window focus & pending composition**: `tools/fixtures/macos-events.rs`'s `CYCLE_WINDOW` posted synthetic `Command-grave` (`key=50, flags=1<<20`) via `CGEventPostToPid`, bypassing macOS WindowServer's `_HIWindowCycle`: - When `processingCompose == false`, `EmacsView.keyDown(with:)` (`platform/macos/nsterm.swift:8539-8570`, matching `src/nsterm.m:7349-7394`) routes `s-\`` through Lisp `other-frame` (`ns_focus_frame` under `block_input()`), intermittently desynchronizing Frame B's `IMKInputSession` so `interpretKeyEvents` falls back in-process (`insertText("n")` in `< 0.5 ms` while `selectedKeyboardInputSource` already reports Pinyin). - When `processingCompose == true` (`pending-focus-transfer`), `EmacsView.keyDown(with:)` (`platform/macos/nsterm.swift:8502,8585-8606`, matching `src/nsterm.m:7288,7410-7425`) skips `if !processingCompose`, strips `.command`, and hands bare `` ` `` to `interpretKeyEvents`, inserting literal `` ` `` into Frame A without switching windows. - Posting a real HID titlebar click (`CGEventCreateMouseEvent` via `CGEventPost(kCGHIDEventTap)`) transitions native WindowServer focus cleanly in both states, and `[viewA.inputContext deactivate]` cancels pending `"ni"` on Frame A (`setMarkedText("") -> deleteWorkingText()`, `marked = false`) within `~4 ms`. Sending `Escape` (`key=53`) unconditionally afterward at `tools/test-macos-ime.py:240` queues an uncomposed `` (`ESC` Meta prefix) on Frame B that consumes the first character of the next `"你好"` commit (`'你好好'`). 2. **`GA1` External Finder Drag (`IV-A4` / `SD-A9`)**: - `EmacsView.draggingEntered`, `prepareForDragOperation`, `draggingUpdated`, and `performDragOperation` (`platform/macos/nsterm.swift:9046-9210`) match `src/nsterm.m:9452-9654`. In Finder list view, dragging `AXTextField` drags filename text rather than initiating a file-URL drag; in Finder icon view, dragging the file's `AXImage` (`>= 16x16`) via `CGEventPost(kCGHIDEventTap)` initiates a genuine `NSPasteboardTypeFileURL` session that fires both `draggingUpdated` (`ns-drag-motion-function` with live frame and numeric `x`/`y`) and `performDragOperation` (opening the exact UTF-8 file). 3. **`GA3` Three Effective Blocking Eglot Cases (`test/lisp/progmodes/eglot-tests.el`)**: - **`eglot-test-tramp-test` & `eglot-test-tramp-test-2`**: `eglot-tests.el:1507` prepends `'tramp-own-remote-path` (inheriting process `PATH`), and `lisp/progmodes/eglot.el:1802-1805` wraps remote servers in `/bin/sh -c "stty raw > /dev/null; "`. In `g3-555-frozen2`'s 108-entry `PATH`, Homebrew GNU coreutils `gnubin/stty` (`9.12`) precedes `/bin/stty`. On Darwin, GNU `stty raw` leaves `ECHO` (`0x8`) and `IEXTEN` (`0x400`) enabled (`c_lflag = 0x44b` vs BSD `/bin/stty raw` `0x41`), overflowing the Darwin PTY input/echo buffer at byte `3811` of Eglot's `initialize` JSON-RPC request (`JSON parse error: [3:3809, byte=3811]` in retained `stderr.log` on both sides -> `[1] timed-out request ':initialize'`). Pinning `stty=/bin/stty` makes both remote tests pass on both the installed reference and the candidate. - **`eglot-test-try-completion-inside-symbol-2`**: Upstream commit `1143cf09a339d57051a4341103c9e342d8876649` (`bug#73857`) advertises `:insertReplaceSupport t` (`lisp/progmodes/eglot.el:1125`) and unconditionally applies `InsertReplaceEdit`'s `replace` range (`lisp/progmodes/eglot.el:4149-4150`). Apple `/usr/bin/clangd` (`21.0.0`) returns `TextEdit` (`"foo"`), so all 47 cases in `eglot-tests.el` pass on both sides; LLVM `clangd` `23.1.5` returns `InsertReplaceEdit` (`insert: "foo"`, `replace: "foo123"`), replacing `"foo123"` with `"foobar"` and failing `(should (looking-at "123"))` identically on both sides (addressed upstream in `bug#81912`, commit `7586a71d7c465e3a403dd6f04b76cac38a995189`). ### 2. Exact Stage I file, symbol and interface changes (Step A) | ID | File / symbol | Exact contract, inputs, outputs and lifecycle | Cases | | --- | --- | --- | --- | | S1-D1 | `platform/macos/nsterm.swift:8158 ns_input_trace` | Add `"clientIsCurrentInputContext": NSTextInputContext.current === inputContext` to the opt-in `FEMACS_INPUT_TRACE` JSONL record alongside `clientHasInputContext` and `selectedKeyboardInputSource`. Read-only observation; zero effect when `FEMACS_INPUT_TRACE` is unset and zero mutation of responder/IME state. | S1-A1, S1-A2 | | S1-D2 | `tools/fixtures/macos-input-source.rs::main`; `tools/fixtures/macos-events.rs::main`; `tools/test-macos-ime.py::focus_frame`, `run_scenario`, `client_source_sample` | Add `activate PID` to `macos-input-source.rs` (`AXUIElementSetAttributeValue(app, "AXFrontmost", kCFBooleanTrue)` + 200 ms settle). Add `CLICK_POINT\t\t` to `macos-events.rs` (`CGEventCreateMouseEvent` `MouseMoved` + `LeftMouseDown` + `LeftMouseUp` via `CGEventPost(kCGHIDEventTap)`), retaining `CYCLE_WINDOW` and keystroke lines. In `test-macos-ime.py`: call `source('activate', process.pid)` after `native-startup` when not yet active; focus target frame in `focus_frame` via `CLICK_POINT` on its titlebar center computed from `windowFrame` and `CGDisplayBounds(CGMainDisplayID())` (retaining `CYCLE_WINDOW` fallback only if `windowFrame` is absent); send `Escape` (`[53]`) after `pending-focus-transfer` only if `snapshot().get('marked')` is still true, recording `focus_loss_cleared_marked` in `focus_loss_observation`; include `clientIsCurrentInputContext` in `observe_client_source`. | S1-A1, S1-A2 | | S1-D3 | NEW `tools/test-macos-drag.py` (`run_drag_acceptance`, `main`); `tools/fixtures/macos-drag.el` (unchanged) | CLI `--app Path --out Path [--timeout float]`. Verify unlocked console (`CGSessionCopyCurrentDictionary`) and `AXIsProcessTrusted()`. Create owned source folder + UTF-8/Chinese `femacs-drag-sample.txt`, open owned Finder window in `icon view` at `{40, 80, 580, 480}`, launch `--app` via `tools/fixtures/ime-launch.swift` with `macos-drag.el` and `FEMACS_INPUT_TRACE`, verify `proc_pidpath(pid)`, locate `AXImage` (`>= 16x16`) in Finder and target window bounds, post real HID drag (`MouseMoved` -> `LeftMouseDown` -> 25 `LeftMouseDragged` steps -> `LeftMouseUp`), verify `draggingUpdated` + `performDragOperation` in `callbacks.jsonl`, live frame + numeric `x`/`y` in `FEMACS_DRAG_REPORT`, exact file contents in `FEMACS_DRAG_READY`, unchanged binary/dump SHA-256 before/after, and close both the launched editor and only the owned Finder window ID. | S1-A3 | | S1-D4 | `tools/functional-strict-probe.py` (`resolve_pinned_tools`, `build_pinned_bin`, `main`); `tools/fixtures/stable-suite-runner.el` (`stable-suite--install-eglot-server-observer`) | Extend `functional-strict-probe.py` with repeatable `--pin-tool NAME=/abs/path` and `--base-path PATH` (default `/usr/bin:/bin:/usr/sbin:/sbin` when `--pin-tool` is supplied) plus optional `--case-ids ID[,ID...]`. Validate regular non-setuid executable target, record lexical path, `realpath`, `bytes`, `sha256`, and bounded `--version` probe (`exit_code`, `first_line`), stage `/pinned-tools/` symlinks, set deterministic `PATH=/pinned-tools:` identically for both `reference` and `candidate`, and pass `FEMACS_STRICT_SERVER_OBSERVATION=/results//eglot-servers.jsonl`. In `stable-suite-runner.el`, when `FEMACS_STRICT_SERVER_OBSERVATION` is set to a path under `out`, attach a read-only `eglot-connect-hook` observer recording `test_id`, `remote_method`, `process_command`, `"Running language server: ..."` line from `jsonrpc-events-buffer`, and `eglot--server-info` (`:name`, `:version`). Record `pinned_tools`, `effective_path`, and per-side `started_servers` + pair comparison (`pair_verdict`) in `adjudication.json`. | S1-A5, S1-A6 | | S1-D5 | `tools/stable-source-rules.py` (`expand`); `tools/stable-classification.py` (`_accept_rule`, `_capture_failing_rule`, `_component_version_applicability`); `tools/fixtures/stable-classification-source-rules.json` | Add two source- and event-bound gates under existing approved categories: (1) `invalid_gate.kind == "remote-unqualified-stty-raw-echo"` (`upstream-invalid-test`) for `eglot-test-tramp-test{,-2}`, anchoring `eglot-tests.el:673-685,1505-1540` and `lisp/progmodes/eglot.el:1795-1807`, requiring `statuses == ['failed', 'failed']`, matching `(error "[eglot] Timed out after 10 seconds")` condition, `gnubin` ahead of `/bin` in `stable-suite-inputs.json`, matching `stty raw > /dev/null` + `JSON parse error` + `timed-out request` in both sides' retained `stderr.log`, passing same-file `eglot-test-basic-completions`, and a bound pinned-tool strict-probe receipt (`supporting_evidence` / `--eglot-probe`) where `stty=/bin/stty` makes both remote cases pass on both sides with recorded server identity; (2) `version_gate.kind == "external-lsp-insert-replace-edit"` (`proven-version-evolution`) for `eglot-test-try-completion-inside-symbol-2`, anchoring `eglot-tests.el:673-772` and `lisp/progmodes/eglot.el:1120-1130,4144-4154`, binding upstream commit `1143cf09a339d57051a4341103c9e342d8876649` (`bug#73857`) and upstream fix commit `7586a71d7c465e3a403dd6f04b76cac38a995189` (`bug#81912`), requiring `statuses == ['failed', 'failed']`, matching `(looking-at "123")` failure condition, passing same-file `eglot-test-try-completion-inside-symbol` and `eglot-test-basic-completions`, and two bound pinned-tool strict-probe receipts proving `clangd 23.1.5` reproduces the exact matching failure while `clangd 21.0.0` passes all 47 `eglot-tests.el` cases on both sides. | S1-A6, S1-A7 | | S1-D6 | Clean tracked export (`git archive`) + `xtask build-terminal` + `xtask build-macos` + relocation + `g3-effective-blocking` refresh | Build both standard products from a clean tracked-only export without `emacs/`, caches or old objects, rebuild root `build/terminal/port/src/emacs` and publish `dist/macos/Femacs.app` from the identical Stage I snapshot, verify moved-bundle relocation (`open -n` / `--batch` with source export hidden), strict `codesign --verify --deep --strict`, `spctl --assess` local-trial boundary, and explicit coverage mapping from `g3-555-frozen2` + `g3-subset-native-1` + Stage I strict probes onto the delivered products. | S1-A4, S1-A8 | ### 3. Stage I case matrix (`S1-A1..S1-A8`) - `S1-A1` (Helper & protective units): `native_window_ready`, `client_source_sample` (`clientIsCurrentInputContext`), `test-macos-drag.py` output/Finder-cleanup/motion validators, `functional-strict-probe.py` pin-tool validation/rejection (missing binary, directory, non-executable, duplicate tool, mismatched server observation), and `stable-classification.py` positive/negative counterexample checks for both new Eglot gates. - `S1-A2` (`GA1` IME & TTY): Real desktop `tools/test-macos-ime.py --mode steady`, `switch`, and `multi` (Frame A + Frame B composition, commit, cancellation, pending-composition focus transfer, save and clean exit, original input source restored) plus 6-case `tools/test-goal-stability.py --mode tty` on the rebuilt Stage I products. - `S1-A3` (`GA1` External Finder Drag): Real desktop `tools/test-macos-drag.py` from an owned Finder icon-view window into `Femacs Drag Target`, verifying `draggingUpdated` live-frame numeric coordinates, `performDragOperation`, exact opened UTF-8/Chinese file bytes, and owned window/process cleanup. - `S1-A4` (`GA2` Clean Tracked Export, Relocation & Gatekeeper Boundary): Fresh `git archive` tracked-only export builds `build-terminal` and `build-macos` using a freshly installed pinned `tree-sitter 0.27.1` prefix (`tools/toolchain-pins.py install`); relocated `Femacs.app` passes startup/resource/library checks with the export hidden; strict `codesign` passes; `spctl --assess --type execute -vv` rejection is recorded honestly as the ad-hoc local-trial boundary; root `build/terminal/port/src/emacs` and `dist/macos/Femacs.app` match the Stage I source snapshot and pass `tools/local-acceptance.py --gui --ime`. - `S1-A5` (`GA3` Pinned-Tool Strict Probes): Run `tools/functional-strict-probe.py` on `test/lisp/progmodes/eglot-tests.el` with (a) `stty=/bin/stty` + `clangd=/opt/homebrew/opt/llvm/bin/clangd` (`23.1.5`) and (b) `stty=/bin/stty` + `clangd=/usr/bin/clangd` (`21.0.0`), capturing tool `realpath`/`sha256`/`--version` and actual started local + Tramp `eglot--server-info` on both sides; also run affected strict-probe files against the refreshed Stage I Cocoa candidate. - `S1-A6` (`GA3` Scoped Classification & Effective Blocking `3 -> 0`): Expand updated `stable-classification-source-rules.json` (`575 -> 578` source rules), run scoped assembly on `g3-555-frozen2` conserving raw failures `574` (`g3-subset-native-1` `37` unchanged), verify effective blocking drops `3 -> 0` with `0` capture/structural failures. - `S1-A7` (Counterexample & regression gates): Verify mutating any Eglot condition, removing `/bin/stty` pin proof, or mismatching `clangd` probe status is rejected by `stable-classification.py`; run `tools/check-own-voice.py` and `tools/test-repository-bootstrap.py`. - `S1-A8` (Cleanup & signed Stage I delivery): Retire Stage I temporary build/export/probe caches with per-item SHA-256 report in `maintenance/cleanup/`, update `docs/current-state.md` and `docs/status.md`, sign-commit (`git commit -S` with `[skip ci]`), push `origin/master`, and verify signature. - [x] S1-C0: complete Stage I (`GA1–GA3`) source-bound design and case matrix (Step A). - [x] S1-C1: write all Stage I acceptance drivers and unit test cases without running (Step B). - [x] S1-C2: write all Stage I production and tooling implementation without running (Step C). - [x] S1-C3: run consolidated Stage I build, clean-export, GUI/IME/drag/TTY, pinned Eglot probes, classification closure, unit protections, cleanup report and signed `[skip ci]` delivery (Step D; see [Stage I closure receipt](../maintenance/releases/2026-11-20-stage1-ga1-ga2-ga3-closure.md) and [CLN270](../maintenance/cleanup/reports/2026-11-20-270-consumed-stage1-delivery-and-probes.md)). ## Solo Continuation Stage II (`GA4`) Source-Bound Design (`6065cf1b`, 2026-11-20) Re-audit Stage II (`5118ed08`) reader/replacement/support-matrix/recovery contracts against all post-`5118ed08` changes through `6065cf1b`, reconcile the `47` untracked local cleanup manifests (`2026-11-11..16`, `CLN227–CLN269`), and retire consumed superseded build/release outputs without touching Stage III runtime comparison inputs. | ID | File / symbol | Exact contract, inputs, outputs and lifecycle | Cases | | --- | --- | --- | --- | | S2-D1 | `tools/test-macos-stability.py`, `tools/test-functional-strict-probe.py` | Re-verify `P-102` thin-wrapper policy across all `15` `tools/*.sh` scripts (`<= 25` lines each, zero nested `controlled-run`, all `6` retired bring-up files absent) and remove empty `build/{stability-unit,strict-probe-unit}` scratch parent directories in `tearDownClass`. | S2-A1, S2-A2 | | S2-D2 | `docs/support-matrix.md`, `docs/retired-scaffolding.md` | Synchronize macOS arm64 terminal & Cocoa evidence boundary with `6065cf1b` (external Finder drag, multi-window IME, 6-case no-controlling-TTY, clean `git archive` relocation) and Android API36 `5118ed08` `device22` normal-product acceptance while preserving the uncertified physical API21 device boundary and retaining all non-retired targets (`Linux`, `Windows`, `Haiku`, other Android ABIs). | S2-A1, S2-A2 | | S2-D3 | `maintenance/cleanup/reports/2026-11-16-269-superseded-single-product-gc-candidate.md`, `maintenance/cleanup/reports/2026-11-20-271-historical-manifest-disposition-and-g4-reaudit.md`, `maintenance/cleanup/LOG.md` | Publish the missing `CLN269` prose report cited by `docs/status.md`, record per-file SHA-256 / disk bytes / raw bytes / line count / prose report / reason / recovery for all `47` untracked local `maintenance/cleanup/manifests/2026-11-11..16-*` files (`46,990,560` disk bytes, `0` personal paths) per `57101ad7` + `ai-storage`, dispose of those `47` untracked local ledgers, and retire consumed superseded trees (`build/runtime/ime-diag-1`, `build/manuals/*`, `dist/releases/*`, superseded `dist/candidates/{g4-android-8,g4-android-9,g4-gc-root-trace-2,g4-macos-2}`, `build/macos-acceptance`, empty `build/*-unit` dirs) while keeping `build/runtime/{frozen-2,native-2,native-collector-1}`, `dist/candidates/g4-android-10`, Stage I products, and Stage I receipts for Stage III. | S2-A3, S2-A4 | - `S2-A1`: Unit contracts (`test-macos-stability.py`, `test-functional-strict-probe.py`) verify retired scaffolding absence, thin shell wrappers, non-retired platform retention, and clean unit scratch teardown. - `S2-A2`: Existing G4 verification suites (`test-modernization-tools.py`, `test-tooling-modernization.py`, `test-g4-platform-floor.py`, `test-g4-review-regressions.py`, `cargo test -p xtask`, `check-own-voice.py`, `test-repository-bootstrap.py`) pass on `6065cf1b` + Stage II edits. - `S2-A3`: All `47` untracked `maintenance/cleanup/manifests/2026-11-11..16-*` files and superseded `build/`/`dist/` trees are hashed, verified zero-consumer, disposed of, and documented in `CLN271` + `LOG.md`, leaving zero untracked files in `git status --short`. - `S2-A4`: Stage II signed `[skip ci]` commit verified and pushed to `origin/master`. - [x] S2-C0: complete Stage II (`GA4`) source-bound re-audit and manifest-disposition design (Step A). - [x] S2-C1: write Stage II reader/wrapper/scratch-cleanup unit cases without running (Step B). - [x] S2-C2: write Stage II support-matrix, retired-scaffolding, unit teardown and `CLN269` prose updates without running (Step C). - [x] S2-C3: run affected G4 suites + `xtask` tests, dispose of the `47` untracked manifests and superseded trees with `CLN271` report, verify clean `git status --short`, and sign-push `[skip ci]` delivery (Step D; see [CLN271](../maintenance/cleanup/reports/2026-11-20-271-historical-manifest-disposition-and-g4-reaudit.md)). ## Solo Continuation Stage III (`GA5–GA8`) Source-Bound Design (`60ce6ecd`, 2026-11-20) Complete the Lisp runtime profiling (`GA5`), interpreter/bytecode/native evaluation and decision (`GA6`), generational collector evaluation and decision (`GA7`), and final delivered-product speedup/stability/delivery audit (`GA8`) strictly in `A -> B -> C -> D` order without premature execution inside `A/B/C`. ### 1. Source-bound runtime baseline and `Pre-A` findings 1. **Unchanged VM/collector source identity across `26d81b95..60ce6ecd`**: - Every runtime source unit (`src/eval.rs`, `src/bytecode.rs`, `src/comp.rs`, `src/alloc.rs`, `src/data.rs`, `src/fns.rs`, `src/lread.rs`, `src/print.rs`, `src/sort.rs`, `src/search.rs`, `src/editfns.rs`, `src/pdumper.rs`, `src/dynlib.rs`, `src/runtime_gc_collector.rs`, `src/runtime_gc_observation.rs`, `src/include/*.rs`) in `60ce6ecd` is byte-identical to `26d81b95`, binding: - Delivered standard products: `build/terminal/port/src/emacs` (`a0dd02e1…`) and `dist/macos/Femacs.app` (`02f5adaf…`). - Runtime comparison cohort: `build/runtime/native-2/port/src/emacs` (`variant=native`, `observer=true`), `build/runtime/frozen-2/port/src/emacs` (`variant=collector`, `observer=true`), and `build/runtime/native-collector-1/dist/Femacs.app` (`variant=native-collector`, `observer=true`). 2. **External-resource installed reference bundle layout (`P462` / `P464` gap in `runtime-profile.py` and `bench.py`)**: - The authorized `32.0.50` installed reference `.app` bundle stores its portable dump and Lisp directory in its shared package prefix rather than `Contents/Resources/{lisp,libexec}`. In `tools/runtime-profile.py:121-143`, `profile_inputs` required `Contents/Resources/lisp` and a bundle-internal `.pdmp`, which would fail candidate `6` (`reference-interpreted`) in `tools/fixtures/runtime-comparison-plan.json`. Likewise, `tools/bench.py:187` hardcoded `binary.with_suffix('.pdmp')`, rejecting both `dist/macos/Femacs.app/Contents/MacOS/Femacs` (`Contents/Resources/libexec/Femacs.pdmp`) and the installed reference `.app` executable. 3. **`G6` & `G7` runtime architecture and candidate trade-offs**: - **Baseline VM & mark-sweep GC (`8babaa66`, `d22daf1e`, `87fe18eb`, `1a8f68e4`)**: `src/eval.rs` (`eval_sub`, `Flet`, `Fsetq`, `funcall_subr`), `src/bytecode.rs` (`exec_byte_code` cold-outlined slow paths, inline `do_varref!`/`do_varset!`/`do_varbind!`/`do_unbind!`/`do_call!`, peephole loop/branch/cons fusions, `bcall0` unwind fast path), `src/data.rs`/`src/fns.rs`/`src/sort.rs`/`src/lread.rs`/`src/editfns.rs`, and `src/alloc.rs` (inline `pdumper_*` bitmap checks, immediate fixnum/`nil`/unused-hash-key mark skips, `sweep_conses` all-dead block release) ship in the standard `build-terminal` and `build-macos` products while preserving observable Lisp semantics, closure hooks (`P453`), and indirect-call backtrace frames (`P458`). - **Opt-in `libgccjit` native backend (`G6`, `src/comp.rs`, `xtask/src/runtime_backend.rs`)**: Compiles Lisp functions to `.eln` shared objects (`SUBRP` + `native-comp-function-p` = `t`), accelerating numeric/call-heavy Lisp (`bytecode` sum `0.26 ms` vs `7.01–8.20 ms` interpreted; `gc-churn` `100.6–115.0 ms` vs `212.5–239.8 ms`), while requiring an external `libgccjit` + `gcc`/`ld` driver toolchain (`emutls_w` link dependency when `PATH` omits Homebrew `gcc`) and adding ~`44.8 ms` vs ~`30.9 ms` startup + `.eln` compile latency. Standard standalone macOS builds keep `HAVE_NATIVE_COMP=undefined` (`(native-comp-available-p)` -> `nil` clean fallback) while `xtask runtime-build --variant native --backend-prefix ` retains the verified opt-in native build. - **Opt-in non-moving generational (`Young`) cons collector (`G7`, `src/runtime_gc_collector.rs`, `docs/g7-young-root-store-binding.md`, `docs/gc-young-cadence.md`)**: Complete root, `XSETCAR`/`XSETCDR` write-barrier, `XCONS` escaped-block `raw_tainted`, `dlopen` `UNKNOWN_PRODUCER` (reason 8), foreign-thread `FOREIGN` (reason 7), `pdumper`, weak-table, finalizer, and lead-window `CADENCE_PENDING` Automatic cadence (`reason 0` minors, 3-minor `reason 4` Full boundary) implementation. Across `runtime-profile.el` (`53` real Automatic minors per round), non-moving `Young` incurs `1.52x` `gc-churn` and `1.53x` `gc-retained` wall time vs `major` control because phase `22` (`oldbits` revival) + phase `23` (frozen non-cons registry root traversal) + full-block sweeping outweigh static-root savings without young-space compaction. `Young` is therefore **rejected as default** (never claimed as a shipped default generational GC) and retained only behind `xtask runtime-build --variant collector` (`femacs_gc_generational`) with complete source/test/evidence archival. ### 2. Exact Stage III file, symbol and interface changes (Step A) | ID | File / symbol | Exact contract, inputs, outputs and lifecycle | Cases | | --- | --- | --- | --- | | S3-D1 | `tools/runtime-profile.py` (`_has_macho_magic`, `probe_bundle_runtime_inputs`, `profile_inputs`, `artifacts`, `main`); `tools/runtime-comparison.py` (`validate_plan`, `candidate_command`) | Extend `profile_inputs(binary, dump=None, lisp_root=None)` and `artifacts(binary, dump=None, lisp_root=None)` plus CLI `--lisp-root` (`runtime-profile.py`) and optional candidate `lisp_root` (`runtime-comparison.py`). When `binary` is inside `Contents/MacOS/` of an `.app` bundle, has a real Mach-O header, and lacks bundle-local `Contents/Resources/lisp` or a single bundle-local `.pdmp` (`len(found) == 0`), run one bounded 15s `-Q --batch` self-probe in an isolated temp `HOME`/`TMPDIR` reading `(cdr (assq 'dump-file-name (pdumper-stats)))` and `(locate-library "emacs-lisp/bytecomp")` to bind the binary's own dump file and Lisp root. Preserve ambiguity rejection (`len(found) > 1`) and non-Mach-O unit-test error contracts. | S3-A1, S3-A3 | | S3-D2 | `tools/bench.py` (`_has_macho_magic`, `discover_dump`, `main`) | Add `discover_dump(binary, explicit=None)` supporting adjacent `.pdmp`, `.app` bundle `Contents/{Resources/libexec,MacOS/libexec}/.pdmp`, and bounded 15s `-Q --batch` `pdumper-stats` discovery for external-prefix installed `.app` bundles, plus optional `--dump` / `--ref-dump`. Record `dump` path + `dump_sha256` before and re-verify after all rounds; record per-round `load_per_round`, `max_load_per_core`, and `quiet` (`all(load <= args.max_load_per_core for load in loads)`) alongside entry `load_per_core`. Keep `sys.argv` unchanged when `dump == binary.with_suffix('.pdmp')`. | S3-A1, S3-A4 | | S3-D3 | NEW `tools/fixtures/ga8-delivered-comparison-plan.json` | Declare `femacs-runtime-comparison-plan-v1` (`warmup: 2`, `rounds: 7`, `max_load_per_core: 0.10`) comparing delivered `dist/macos/Femacs.app/Contents/MacOS/Femacs` and `build/terminal/port/src/emacs` against the installed `32.0.50` reference `.app` across matched `interpreted` and `bytecode` modes (`delivered-cocoa-vs-reference-interpreted`, `delivered-cocoa-vs-reference-bytecode`, `delivered-terminal-vs-reference-interpreted`, `delivered-terminal-vs-reference-bytecode`), while keeping `tools/fixtures/runtime-comparison-plan.json` unchanged for the 6-candidate `GA5–GA7` comparison. | S3-A1, S3-A4 | | S3-D4 | `tools/test-runtime-comparison.py`, `tools/test-release-baseline.py`, `tools/test-modernization-tools.py`, `maintenance/tooling-inventory.json` | Add unit cases for `lisp_root` plan/command forwarding, external-resource Mach-O bundle input discovery vs non-Mach-O/ambiguous rejection, `.app` bundle `discover_dump` + post-run dump hash verification + `load_per_round`/`quiet` reporting in `bench.py`, and synchronize `maintenance/tooling-inventory.json` hashes and readers. | S3-A1 | | S3-D5 | `GA6` & `GA7` semantic, lifecycle, barrier, cadence and component verification | Execute on the `60ce6ecd`-identical runtime cohort and delivered standard products: `runtime-components.py` + `test-runtime-contracts.py` (`28/28` B-vectors), `stable-compat.py --reference-version 32.0.50` (`48/48` across terminal, Cocoa, and installed `32.0.50` reference), `runtime-hotpath-protection.el` + `runtime-call-frames-functional.el` + `bytecode-runtime.el` across all 3 products, `runtime-native.el` + `runtime-native-lifecycle.el` on `native-2`, and `runtime-gc.el` + `runtime-gc-fallback.el` + `runtime-gc-root-phases.el` + `gc-young-cadence.el` + `g7-native-write-barrier.el` on `frozen-2` and `native-collector-1`. | S3-A2 | | S3-D6 | `GA5–GA8` workload/GC measurements, quiet-host gate, final cleanup (`CLN272`), documentation & reverse audit | Run `runtime-comparison.py` on `runtime-comparison-plan.json` (6 candidates) and `ga8-delivered-comparison-plan.json` (6 candidates) plus paired `bench.py` (`eval.el` 10 cases + startup, terminal & Cocoa vs installed `32.0.50` reference). Enforce strict `quiet` (`load_per_core <= 0.10`) before promoting any timing/speedup conclusion; record every round, median/MAD/IQR/p95, GC count/pauses/phases `22/23/24`, survival/remembered-set/cadence, peak RSS, and startup. Upon closing all `GA5–GA8` evidence, publish Stage III release receipt + `CLN272` retiring all consumed `build/`, `.femacs-cache/`, and session-cache trees while retaining verified working `build/terminal/port/src/emacs` and `dist/macos/Femacs.app`, sign-push `[skip ci]`, and reverse-audit `GA1–GA8`. | S3-A3..S3-A6 | ### 3. Stage III case matrix (`S3-A1..S3-A6`) - `S3-A1` (Tool & protective unit contracts): `test-runtime-comparison.py`, `test-release-baseline.py --component-only`, `test-modernization-tools.py`, `test-tooling-modernization.py`, `test-runtime-measurement-contracts.py`, `test-runtime-measurement-report.py`, `test-runtime-phases.py`, `cargo test -p xtask`, `check-own-voice.py`, and `test-repository-bootstrap.py`. - `S3-A2` (`GA6` / `GA7` / `GA8` semantic, lifecycle, barrier & differential gates): `runtime-components.py` + `test-runtime-contracts.py` (`28/28`), `stable-compat.py` (`32.0.50` three-product `48/48`), `runtime-hotpath-protection.el` (`10` cases × 3 products), `runtime-call-frames-functional.el` (`7` cases × 3 products), `bytecode-runtime.el` (`10` cases × 3 products), `runtime-native.el` + `runtime-native-lifecycle.el` (`native-2`), and `runtime-gc.el` + `runtime-gc-fallback.el` + `runtime-gc-root-phases.el` + `gc-young-cadence.el` + `g7-native-write-barrier.el` (`frozen-2` & `native-collector-1`). - `S3-A3` (`GA5` / `GA6` / `GA7` 6-candidate comparison): `tools/runtime-comparison.py --plan tools/fixtures/runtime-comparison-plan.json` (`2` warmup + `7` measured rounds under `load_per_core <= 0.10` for promotion; any `load_per_core > 0.10` diagnostic run kept strictly `promotion_grade=false`). - `S3-A4` (`GA8` delivered-product comparison vs installed `32.0.50` reference): `tools/runtime-comparison.py --plan tools/fixtures/ga8-delivered-comparison-plan.json` (`2` warmup + `7` measured rounds) and paired 7-round `tools/bench.py` (`dist/macos/Femacs.app` and `build/terminal/port/src/emacs` vs installed `32.0.50` reference) under `load_per_core <= 0.10`. - `S3-A5` (`CLN272` final storage retirement & post-cleanup trial verification): Retire all consumed `build/acceptance`, `build/runtime`, `build/macos`, `build/cargo`, `build/generation`, `.femacs-cache`, `dist/candidates`, and external session caches with full SHA-256/byte accounting in `CLN272`, retaining only working `build/terminal/port/src/{emacs,emacs.pdmp}` (+ `build/terminal/port` runtime links) and `dist/macos/Femacs.app`, and re-verify both trial deliverables start cleanly after cleanup. - `S3-A6` (Final signed delivery & `GA1–GA8` reverse audit): Update `docs/{modernization,runtime-modernization,current-state,status}.md` and `maintenance/releases/`, verify `git status --short` clean, sign-commit (`[skip ci]`), push `origin/master`, verify `git log --show-signature -1`, and reverse-audit `GA1–GA8` against raw receipts. - [x] S3-C0: complete Stage III (`GA5–GA8`) source-bound design and case matrix (Step A). - [x] S3-C1: write Stage III comparison plan and unit/protection test cases without running (Step B). - [x] S3-C2: write Stage III `runtime-profile.py`, `runtime-comparison.py`, `bench.py`, `runtime-component-adapter.rs`, `xtask/src/android/package_tests.rs`, and `tooling-inventory.json` updates without running (Step C). - [x] S3-C3: run consolidated Stage III semantic/lifecycle/barrier/component gates, formal `2+7` / 7-round `GA5–GA8` comparisons (under explicit `2026-11-20` user host-load authorization with `max_load_per_core: 0.10` unchanged), final `CLN272` + `CLN273` cleanup, signed `[skip ci]` delivery, and `GA1–GA8` reverse audit (Step D; see [Stage III closure](../maintenance/releases/2026-11-20-stage3-ga5-ga6-ga7-ga8-closure.md) and [CLN273](../maintenance/cleanup/reports/2026-11-20-273-final-acceptance-runtime-and-cache-retirement.md)).