# Retrain your own Emacs command model The reusable workflow is **collect → train → benchmark → improve data → finalize → use**. Emacs supplies the dashboard; Rust owns the datasets, optimizer, comparisons and artifacts. Training starts from fresh weights. It does not fine-tune or replace the downloaded model in place. Each user project retains an immutable baseline, the original training and calibration data, frozen command and execution benchmarks, authored examples, and every training attempt. Python is not needed for this workflow. ## Install and create a project Follow the [native setup](emacs.md#build-the-native-module), then install the bundled `emacs/lispm-llm-0.3.0.tar` with **M-x package-install-file**. The archive contains inference, the training dashboard and the isolated task runner. To rebuild it: ```sh bash scripts/package-emacs.sh ``` Configure the native module and model directory as in the [Emacs guide](emacs.md), then run **M-x lispm-llm-train-create**. Choose the downloaded model repository as the baseline and a new project directory, such as `~/lispm-training`, under an existing parent. Training uses the repository's `data/training.json`; the command benchmark defaults to `data/benchmark.json`. A prefix argument prompts for alternative training and command benchmark files. The expanded command benchmark includes the original single-action cohorts and 2,256 two-action recombinations. New Emacs projects also freeze `data/emacs-tasks.json` and the package's `lispm-llm-benchmark.el` runner by default. These tasks execute core Emacs operations in a clean batch subprocess and check resulting buffer, window and file states. See the [benchmark definitions](benchmarks.md) for outcome meanings and scope. Customize `lispm-llm-train-emacs-program` to select an absolute Emacs executable, `lispm-llm-train-task-data` for an alternative reviewed suite, and `lispm-llm-train-task-timeout` for its batch timeout. Setting `lispm-llm-train-enable-task-benchmark` to nil before project creation explicitly creates a command-only project. The dashboard shows whether execution testing is configured; changing this option does not change an existing project. The project stores its collection rules in `RULES.md`. Reopen it later with **M-x lispm-llm-train**. Keep projects separate from the model repository's published `data/` and `rust-trained/` directories. Existing projects keep their immutable baseline and benchmark. To adopt the new benchmarks, create a new project and import the old project's reviewed `examples.json`. Resolve any overlap with the new held-out instructions instead of changing frozen data or hashes. A version-two project includes the required task suite; version-one command-only projects remain readable. ## Collect and revise examples Press **a** to add a labeled instruction. Label completion offers the existing 48 actions plus `reject`. A prefix argument marks a hard example for additional sampling. Press **i** to import a JSON file: ```json { "format_version": 1, "examples": [ { "instruction": "please preserve these fresh edits in my current editing buffer", "label": "save-buffer", "hard": true }, { "instruction": "I want a second identical browser tab for side by side reading", "label": "reject", "hard": true } ] } ``` A ready-to-edit example is in [example-user-dataset.json](../data/example-user-dataset.json). It is an example import file; it is not automatically added to shared training. Collection rules: - Label one English operation per supported example. Use JSON double quotes for file names, buffer names, search text and other literal arguments. For example, `please visit the file "notes.el"` can use `find-file`. - Supply the intended label yourself. Predictions are not ground-truth labels. Unsupported operations use `reject`; unfamiliar wording of a supported action should retain that action's label. - The runtime grammar still applies: unsupported negations/connectors and invalid parameter shapes cannot become supported training examples. Unicode belongs inside quoted arguments; the instruction language is English. - Normalized duplicates do not add weight. Conflicting labels, unknown actions, invalid fields and calibration/benchmark overlaps fail without changing data. - Preserve the frozen benchmark, including individual composition clauses and task instructions. Use newly collected wording when improving a failure family; do not copy the reported test sentence into training. To correct labels or remove examples, edit a separate import file and use **C-u i** to replace the authored examples. A normal **i** appends. Replacement preserves the shared corpus, calibration/reference and all older run snapshots. Imports use a generation hash and an atomic write, so concurrent collectors cannot silently overwrite each other. Adding examples expands language coverage within the fixed action vocabulary. Adding a new executable action still requires a reviewed change to the typed catalog and dispatch table; an imported label cannot introduce arbitrary Lisp. ## Standalone native dataset augmentation With the [LibTorch environment](rust.md#build) configured, the native [`prepare-training` example](../examples/prepare-training.rs) can validate a reviewed example file and write a fresh trainer input directly. From the repository root: ```sh mkdir -p experiments cargo run --release --locked --example prepare-training -- \ data/training.json data/benchmark.json data/example-user-dataset.json \ experiments/my-user-training.json cargo run --release --locked -- train \ --data experiments/my-user-training.json \ --output experiments/my-user-model --steps 3200 --seed 42 ``` Edit a copy of `data/example-user-dataset.json` for your own reviewed examples, then substitute its path. Both output paths must be new. The importer preserves the original calibration and selection reference, rejects invalid labels, conflicts and held-out overlaps, and reports the number of added examples. The second command trains from fresh weights using the materialized data. Evaluate each candidate against the same frozen baseline benchmarks before use. For a task-enabled project, supply its `frozen/evaluation.json` as the benchmark argument to reserve task prompts too, or import through the Emacs dashboard, which manages that boundary and the comparison/finalization records for you. ## Train, compare and iterate Press **t** and choose steps and seed. Defaults are 3,200 steps and seed 42. The native job trains in the background and reports step, loss and calibration selection evidence. **k** requests cancellation; closing the dashboard cancels and releases its active job. Cancellation is cooperative between native work units. Once an artifact is committed, a late cancellation leaves it completed. Training uses shared rows plus the project's authored examples. The original calibration prefix, selection reference and confidence ceilings stay unchanged. Each run snapshots its data before training. Failed and cancelled runs remain visible; a run with no eligible calibration checkpoint produces no usable model. Press **b** to compare a trained run with the baseline. Both models use the exact same frozen command benchmark bytes and their own saved admission thresholds. When configured, the same job also evaluates both artifacts against the frozen task suite and runner in isolated batch Emacs processes. **r** shows the latest result; **C-u r** selects a persisted benchmark. Reports remain available after reopening the dashboard and include: - Supported correct actions, wrong actions and refusals. - Unsupported false acceptances and refusals. - Novel-word outcomes, per-action details and concrete failure cases. - Whole-program correctness for two-action cohorts, including order and arguments. - Task success, wrong final state, refusal, execution error and blocked action, with one-step/two-step and scenario breakdowns when the task suite is enabled. - Model/configuration/data hashes and the candidate's training identity; task reports also identify the runner, Emacs executable and Emacs version. The default completion rule checks every corpus: supported correctness cannot decrease, supported wrong actions or refusals cannot increase, and unsupported false acceptance cannot increase. Novel-word supported coverage must also hold. The execution gate additionally requires that task success does not fall and that each failure category does not rise, overall and within each step-count and scenario group. Missing required task evidence or a runner failure cannot pass finalization. A task is successful only when its resulting state matches the reviewed goal; correct-looking Lisp alone is insufficient. An ineligible candidate remains available for inspection and another iteration; it cannot replace the active model through the workflow. Improve examples using fresh evidence, revise the authored set, then train a new run and compare again. Repeatedly inspected benchmark results are regression measurements, not new blind-test evidence. For a genuinely new held-out benchmark, create a new project with a separately prepared evaluation file. ## Finish and use Press **f** to finalize a reviewed, eligible run. Rust checks the stored report, training snapshot, baseline, benchmark and candidate hashes again, and copies the verified model into an immutable finalized directory. For a task-enabled project, this also checks the task suite, runner and current Emacs executable. After replacing the executable, rerun the benchmark before finalization. Press **u** to explicitly use that finalized run for inference. This updates the current Emacs session's `lispm-llm-model-directory` and clears the cached model. Then use **M-x lispm-llm**, review its proposal and press **C-c C-c** to execute. Use **p** to restore the preceding verified model; the first activation retains the original baseline as its predecessor. The workflow records activation, but does not write your Emacs configuration. Set the chosen directory in your init file if you want it to be the default in future sessions. ## Project layout ```text project.json identities of frozen inputs RULES.md collection and acceptance rules examples.json current authored examples baseline/ original config and weights frozen/training.json shared rows and calibration reference frozen/evaluation.json fixed command benchmark, including reserved task prompts frozen/emacs-tasks.json reviewed task suite, when enabled frozen/emacs-task-runner.el frozen isolated runner, when enabled runs/run-*/examples.json exact authored examples used by this run runs/run-*/training.json materialized trainer input runs/run-*/run.json parameters, generation, status and identities runs/run-*/model/ candidate and training report runs/run-*/benchmark.json baseline/candidate comparison and failures finalized/run-*/ verified inference artifact and evidence binding active.json current selection and rollback identity ``` All model output remains in the existing one/two-action DSL. Dataset generation, run identity and benchmark correctness are separate from whether a particular prediction reflects the user's intent; review proposals before execution. ## C FFI contract The standalone library supports C callers and Lisp CFFI bindings. Emacs uses its native C module ABI with the same Rust request dispatcher. The C declarations are in [lispm_llm.h](../native-api/include/lispm_llm.h): ```c uint32_t lispm_llm_abi_version(void); /* 1 */ char *lispm_llm_request(const char *json_request); void lispm_llm_string_free(char *json_response); ``` Build it with the configured LibTorch environment: ```sh cargo build --release --locked -p lispm-llm-native-api ``` The library is `liblispm_llm_native_api.dylib` on macOS and `liblispm_llm_native_api.so` on Linux, under Cargo's release target directory. When Cargo has a configured target, that directory includes the target triple. The [persistent C example](../native-api/examples/client.c) dynamically loads it and accepts one JSON request per line, retaining jobs across requests. Each call returns `{"ok":true,"result":{...}}` or `{"ok":false,"error":{"code":"...","message":"..."}}`. Input is caller-owned UTF-8 with a terminating NUL; free each returned string exactly once using the matching library function. Keep the library loaded for the process lifetime: releasing a job does not join its worker. Load one runtime per host process, choosing either the Emacs module or the standalone library. | `op` | Additional request fields | | --- | --- | | `version` | none | | `project-create` | `project`, `base_model`, `training_data`, `benchmark_data`, optional `task_suite` | | `project-info` | `project` | | `add-example` | `project`, `generation`, `instruction`, `label`, optional `hard` | | `import-dataset` / `replace-dataset` | `project`, `generation`, `path` | | `train` | `project`, `steps`, `seed`, `threads` | | `benchmark` / `finalize` | `project`, `run`, `threads` | | `run-report` / `activate` | `project`, `run` | | `rollback` | `project` | | `job-poll` / `job-cancel` / `job-release` | `job` | For the default combined workflow, use `data/benchmark.json` as `benchmark_data` and include a task configuration when creating the project: ```json { "op": "project-create", "project": "/absolute/path/to/my-training-project", "base_model": "/absolute/path/to/lispm-llm", "training_data": "/absolute/path/to/lispm-llm/data/training.json", "benchmark_data": "/absolute/path/to/lispm-llm/data/benchmark.json", "task_suite": { "data": "/absolute/path/to/lispm-llm/data/emacs-tasks.json", "runner": "/absolute/path/to/lispm-llm/emacs/lispm-llm-benchmark.el", "emacs": "/absolute/path/to/emacs", "timeout_seconds": 60 } } ``` Every path in `task_suite` must be absolute. The timeout must be between 1 and 3,600 seconds. Task JSON and runner bytes are copied into the project and bound by hashes; task instructions and clauses are also reserved against authored imports. Omitting `task_suite` explicitly creates the legacy command-only workflow. For configured projects, `benchmark`, `run-report` and `finalize` all include the execution evidence; a caller cannot skip that gate by omitting it from a later request. Paths must be absolute. `generation` is the SHA-256 string returned by `project-info`; `run` is a generated string ID. `train`, `benchmark` and `finalize` return `{"job":123}` immediately. Poll to obtain `queued`, `running`, `cancelling`, `completed`, `cancelled` or `failed`, plus the latest `progress`, terminal `result` and `error`. Release every job when finished; at most 128 unreleased handles are retained. Releasing an active job requests cancellation. The JSON request limit is eight MiB; imported dataset files use an explicit path. The first numerical operation fixes the process-wide LibTorch CPU thread count. Training serializes RNG mutation with model loading and benchmarking. Already loaded inference models can continue predicting while training runs; a new model load waits on its worker. No background thread calls an Emacs API.