taskforce-model-foundry 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/tmf.mjs +353 -0
  4. package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
  5. package/docs/acceptance/r1-r7-reconciliation.md +185 -0
  6. package/docs/integration.md +227 -0
  7. package/docs/tutorial.md +336 -0
  8. package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
  9. package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
  10. package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
  11. package/integrations/hermes-plugin/tests/test_register.py +230 -0
  12. package/integrations/openclaw-plugin/index.mjs +27 -0
  13. package/integrations/openclaw-plugin/tools.mjs +70 -0
  14. package/openclaw.plugin.json +24 -0
  15. package/package.json +70 -4
  16. package/scripts/e2e-demo.sh +56 -0
  17. package/src/api.mjs +341 -0
  18. package/src/config.mjs +342 -0
  19. package/src/core/autograd.mjs +451 -0
  20. package/src/core/fsx.mjs +65 -0
  21. package/src/core/hash.mjs +47 -0
  22. package/src/core/rng.mjs +70 -0
  23. package/src/data/clean.mjs +115 -0
  24. package/src/data/dedupe.mjs +125 -0
  25. package/src/data/ingest.mjs +184 -0
  26. package/src/data/pii.mjs +142 -0
  27. package/src/data/pipeline.mjs +183 -0
  28. package/src/data/provenance.mjs +88 -0
  29. package/src/data/split.mjs +193 -0
  30. package/src/data/synth.mjs +198 -0
  31. package/src/eval/evaluator.mjs +124 -0
  32. package/src/eval/gates.mjs +114 -0
  33. package/src/eval/metrics.mjs +90 -0
  34. package/src/export/package.mjs +365 -0
  35. package/src/index.mjs +26 -0
  36. package/src/integrations/hermes.mjs +177 -0
  37. package/src/integrations/openclaw.mjs +154 -0
  38. package/src/jobs/evaluate.mjs +164 -0
  39. package/src/jobs/runner.mjs +323 -0
  40. package/src/jobs/train.mjs +303 -0
  41. package/src/model/lora.mjs +53 -0
  42. package/src/model/tokenizer.mjs +73 -0
  43. package/src/model/transformer.mjs +276 -0
  44. package/src/train/backends/builtin-js.mjs +367 -0
  45. package/src/train/backends/hf-peft.mjs +549 -0
  46. package/src/train/backends/hf_peft_runner.py +326 -0
  47. package/src/train/backends/index.mjs +92 -0
  48. package/src/train/dataset.mjs +56 -0
  49. package/src/train/optimizer.mjs +99 -0
  50. package/src/version.mjs +5 -0
@@ -0,0 +1,227 @@
1
+ # Integration and installation (OpenClaw / Hermes)
2
+
3
+ This document is the host-side contract for mounting Taskforce Model Foundry
4
+ inside an agent runtime. Both adapters are **in-process ES modules** — no
5
+ daemon, no socket, no shelling out to the `tmf` CLI — and both are driven by the
6
+ single action table in `src/integrations/openclaw.mjs`, so a new action appears
7
+ on both hosts at once and the two hosts cannot drift.
8
+
9
+ Verified against the packaged artifact, not the source tree: see
10
+ `artifacts/taskforce-model-foundry/evidence/cp23-r7-pack-install.md` for the
11
+ `npm pack` → clean-directory `npm i` → in-process adapter run that produced the
12
+ numbers quoted here.
13
+
14
+ ## 1. Install
15
+
16
+ The package has **zero runtime dependencies** and needs Node.js >= 20
17
+ (`tmf doctor` enforces the floor). Nothing in an install or a mount touches the
18
+ network.
19
+
20
+ ```bash
21
+ # from a registry (once published)
22
+ npm i taskforce-model-foundry
23
+
24
+ # from a local tarball, which is how the install path was verified
25
+ npm pack # -> taskforce-model-foundry-0.1.0.tgz
26
+ cd /path/to/host
27
+ npm i /path/to/taskforce-model-foundry-0.1.0.tgz
28
+ ```
29
+
30
+ The install provides one bin, `tmf` (`node_modules/.bin/tmf`), and the
31
+ export specifiers below. `package.json` is a fifth, deliberate `exports` entry
32
+ (see §3.1); it is not an API surface.
33
+
34
+ | Specifier | Purpose |
35
+ | --- | --- |
36
+ | `taskforce-model-foundry` | Root export; re-exports the API plus `.openclaw` / `.hermes`. |
37
+ | `taskforce-model-foundry/api` | Programmatic API (`doctor`, `status`, `synthesize`, `train`, `evaluate`, `exportModel`). |
38
+ | `taskforce-model-foundry/integrations/openclaw` | OpenClaw tool-provider adapter. |
39
+ | `taskforce-model-foundry/integrations/openclaw-plugin` | OpenClaw host plugin entry; needs the host-provided `openclaw` package. |
40
+ | `taskforce-model-foundry/integrations/openclaw-plugin/tools` | Host-free tool face (`buildTools`), importable without `openclaw`. |
41
+ | `taskforce-model-foundry/integrations/hermes` | Hermes tool-call adapter. |
42
+
43
+ The root export and the subpaths resolve to the **same module instances**
44
+ (`root.hermes.toolSpecs === hermes.toolSpecs`), so a host may mix specifiers
45
+ without ending up with two copies of the action table.
46
+
47
+ Smoke-check an install before mounting it:
48
+
49
+ ```bash
50
+ ./node_modules/.bin/tmf doctor # exit 0 and "tmf doctor — OK"
51
+ ```
52
+
53
+ `doctor` warns (it does not fail) when no config file is present and when the
54
+ optional `hf-peft` trainer backend is unavailable; the built-in JS trainer
55
+ needs nothing extra.
56
+
57
+ ## 2. Mounting on OpenClaw
58
+
59
+ An OpenClaw host passes an action name plus a params object and gets a
60
+ JSON-serializable envelope back. `invoke` never throws.
61
+
62
+ ```js
63
+ import { register, manifest } from 'taskforce-model-foundry/integrations/openclaw';
64
+
65
+ // `host.registerToolProvider` is called for you when the host exposes it.
66
+ const adapter = register(host, {
67
+ baseDir: '/srv/foundry-workspace', // where jobs/runs/exports live
68
+ configFile: null, // default config for every action
69
+ allowCompute: true, // false = read-only mount, see §4
70
+ });
71
+
72
+ manifest(); // static, side-effect free
73
+ await adapter.invoke('doctor', {});
74
+ ```
75
+
76
+ Envelopes:
77
+
78
+ ```js
79
+ { ok: true, contractVersion: 1, action, result }
80
+ { ok: false, contractVersion: 1, action, error: { code, message } }
81
+ ```
82
+
83
+ ## 3. Mounting on Hermes
84
+
85
+ A Hermes gateway hands over a flat prefixed tool name and a JSON **string** of
86
+ arguments, and shows the model whatever text comes back. `callTool` therefore
87
+ always returns a non-empty `content` string, success or failure.
88
+
89
+ ```js
90
+ import { register, toolSpecs } from 'taskforce-model-foundry/integrations/hermes';
91
+
92
+ const adapter = register(host, { baseDir: '/srv/foundry-workspace', allowCompute: false });
93
+
94
+ toolSpecs(); // OpenAI-style function specs
95
+ await adapter.callTool('tmf_status', '{"jobId":"job-1"}');
96
+ ```
97
+
98
+ `register` adapts to either gateway shape: `host.registerTool({ spec, handler })`
99
+ per tool when available, otherwise `host.registerTools({ tools, handler })`.
100
+
101
+ Envelopes:
102
+
103
+ ```js
104
+ { ok: true, contractVersion: 1, host: 'hermes', tool, action, result, content }
105
+ { ok: false, contractVersion: 1, host: 'hermes', tool, error: { code, message }, content: 'ERROR <code>: <message>' }
106
+ ```
107
+
108
+ Every tool schema is closed (`additionalProperties: false`) and every parameter
109
+ carries a description, so a model cannot invent a param that the adapter would
110
+ then have to reject.
111
+
112
+ ### 3.1 As a Hermes directory plugin
113
+
114
+ `integrations/hermes-plugin/taskforce_model_foundry/` mounts the same adapter
115
+ without any gateway code: Hermes discovers a directory plugin by `plugin.yaml`
116
+ plus a `register(ctx)`, and the plugin asks the Node bridge for the adapter's
117
+ own tool specs, so an action added on the Node side appears on Hermes with no
118
+ Python change.
119
+
120
+ The plugin directory ships in the npm tarball, so the copy works from either an
121
+ installed package or a source checkout; only the source root differs. Point
122
+ `TMF_PKG` at it once and the rest of the snippet is identical:
123
+
124
+ ```bash
125
+ # npm install: ask node where the package landed (works under any node_modules depth)
126
+ TMF_PKG=$(node -p "require('path').dirname(require.resolve('taskforce-model-foundry/package.json'))")
127
+ # source checkout: TMF_PKG=/path/to/taskforce-model-foundry
128
+
129
+ cp -r "$TMF_PKG"/integrations/hermes-plugin/taskforce_model_foundry ~/.hermes/plugins/
130
+ ln -s "$TMF_PKG" ~/.hermes/plugins/taskforce_model_foundry/foundry
131
+ # or: export TMF_FOUNDRY_ROOT="$TMF_PKG"
132
+ ```
133
+
134
+ `require.resolve` is why `"./package.json"` is an explicit `exports` entry: a
135
+ closed `exports` map hides the manifest, and the host then has no supported way
136
+ to locate the installed plugin source.
137
+
138
+ Checkout resolution order: `TMF_FOUNDRY_ROOT`, then `<plugin dir>/foundry`,
139
+ then `~/.hermes/taskforce-model-foundry`. `node` resolution order:
140
+ `TMF_NODE`, then the gateway's PATH, then `~/.local/bin/node`,
141
+ `/usr/local/bin/node`, `/opt/homebrew/bin/node`, `/usr/bin/node`.
142
+
143
+ Three host details are easy to get wrong, and all three were observed on a
144
+ live gateway:
145
+
146
+ - **The gateway's PATH is not your shell's PATH.** A gateway started as a
147
+ service (systemd, launchd, a supervisor) gets a cropped environment, so a
148
+ per-user node — nvm, or `~/.local/bin/node` — is invisible to the plugin
149
+ even though `node -v` works in your terminal. The probe then fails with
150
+ `node-unavailable` and the mount logs `no tools registered`: the plugin is
151
+ loaded and the toolset is simply empty, which looks like `Unknown tool:
152
+ tmf_export` at call time rather than like an install error. The fallback
153
+ locations above cover the common installs; for anything else set
154
+ `TMF_NODE=/absolute/path/to/node` in the gateway's environment (not in your
155
+ shell profile) and reload the gateway. To tell this apart from the
156
+ hyphen/underscore mistake below, check the mount line: a PATH problem logs
157
+ `adapter probe failed (node-unavailable: ...)`, a not-enabled plugin logs
158
+ nothing at all.
159
+
160
+ - **Enable the plugin by its manifest `name`, not its Python package name.**
161
+ The directory is `taskforce_model_foundry` (underscores, importable) but
162
+ `plugins.enabled` is matched against `plugin.yaml`'s `name`, so the entry is
163
+ `taskforce-model-foundry` with hyphens. The underscore spelling is silently
164
+ not enabled.
165
+ - **A successful registration does not prove the tools are callable.** Hermes'
166
+ `tools.registry.dispatch` invokes `entry.handler(args, **kwargs)` — the
167
+ argument dict goes in *positionally* — while other hosts call
168
+ `handler(**kwargs)`. The plugin's handlers accept both shapes and merge them
169
+ (explicit keywords win); a keyword-only handler registers fine and then
170
+ raises `TypeError` on the first real tool call. Likewise `ctx.log` is not
171
+ guaranteed to exist, and anything raised out of `register` rolls back every
172
+ tool the plugin just registered, so the mount logs defensively and reports a
173
+ missing checkout or a failed bridge probe as a skipped mount instead.
174
+
175
+ Both behaviours are pinned by `integrations/hermes-plugin/tests/test_register.py`,
176
+ which `npm test` runs through `test/integration-hermes-plugin.test.mjs` (skipped
177
+ when no Python interpreter is on PATH).
178
+
179
+ ## 4. Action and tool table
180
+
181
+ Six actions, six tools, one table. `compute: true` means the call spends real
182
+ CPU time and writes run artifacts; those are the calls a host should gate.
183
+
184
+ | OpenClaw action | Hermes tool | Compute | Required | Accepted params |
185
+ | --- | --- | --- | --- | --- |
186
+ | `doctor` | `tmf_doctor` | no | — | `configFile`, `requireConfig` |
187
+ | `status` | `tmf_status` | no | `jobId` | `jobId`, `configFile`, `auditTail` |
188
+ | `synthesize` | `tmf_synthesize` | yes | — | `outDir`, `seed`, `count`, `profile` |
189
+ | `train` | `tmf_train` | yes | — | `configFile`, `jobId`, `resume`, `resumeCancelled`, `auditEveryStep` |
190
+ | `evaluate` | `tmf_evaluate` | yes | — | `configFile`, `jobId`, `gates`, `reportFile`, `maxNewTokens` |
191
+ | `export` | `tmf_export` | yes | — | `configFile`, `jobId`, `evalReport`, `outDir`, `version`, `evaluateIfMissing` |
192
+
193
+ **Read-only mount.** `allowCompute: false` keeps the adapter useful for
194
+ inspection while making compute impossible: `doctor` and `status` answer
195
+ normally, and all four compute actions are refused with
196
+ `compute-not-authorized` *before* any handler runs — nothing is written, no
197
+ partial job appears. Mount read-only wherever the host cannot itself vouch that
198
+ training was authorized.
199
+
200
+ ## 5. Error codes
201
+
202
+ Stable codes, shared by both adapters, returned as data rather than thrown.
203
+ A host can branch on `error.code` without parsing messages.
204
+
205
+ | Code | Meaning |
206
+ | --- | --- |
207
+ | `invalid-action` | OpenClaw only: action was not a non-empty string. |
208
+ | `unknown-action` | OpenClaw only: action name is not in the table. |
209
+ | `unknown-tool` | Hermes only: tool name is unprefixed or unknown. |
210
+ | `invalid-json` | Hermes only: the argument string was not valid JSON. |
211
+ | `invalid-params` | Arguments did not decode to a plain object. |
212
+ | `unknown-params` | A param outside the action's accepted list was supplied. |
213
+ | `missing-params` | A required param (today only `jobId`) was absent or null. |
214
+ | `compute-not-authorized` | Compute action on an `allowCompute: false` mount. |
215
+ | `config-error` | Config file missing, unparsable or internally inconsistent. |
216
+ | `action-failed` | Fallback for any other handler failure; message carries the detail. |
217
+
218
+ Handler-specific codes pass through unchanged when the underlying API raises an
219
+ error carrying its own `code`, so this table is a floor, not a closed set — but
220
+ `ok: false` plus a string `error.code` is guaranteed in every case.
221
+
222
+ ## 6. Contract versioning
223
+
224
+ `CONTRACT_VERSION` (currently `1`) appears in every envelope and both
225
+ manifests. It is bumped only on a breaking change to the action set or the
226
+ envelope shape; additive actions and additive params do not bump it. A host
227
+ should treat an unexpected major as "do not mount" rather than degrade.
@@ -0,0 +1,336 @@
1
+ # First run: from install to a trained adapter
2
+
3
+ This tutorial takes about five minutes and needs nothing but Node.js 20+. It
4
+ uses a corpus the tool generates for you, so no private data, no API key and no
5
+ network access are involved. Every step below does real work: the training step
6
+ actually moves weights, and the job state it writes survives the process.
7
+
8
+ ## 1. Install
9
+
10
+ From a clone:
11
+
12
+ ```bash
13
+ git clone https://github.com/ambitioncn/taskforce-model-foundry.git
14
+ cd taskforce-model-foundry
15
+ npm install # there are no runtime dependencies; this just links `tmf`
16
+ node bin/tmf.mjs version
17
+ ```
18
+
19
+ Or as a dependency of your own project:
20
+
21
+ ```bash
22
+ npm install taskforce-model-foundry
23
+ npx tmf version
24
+ ```
25
+
26
+ The rest of this page writes `tmf`. From an install the binary lives in
27
+ `node_modules/.bin`, so write `npx tmf` (or add that directory to `PATH`); from
28
+ a source checkout without a link, write `node bin/tmf.mjs`.
29
+
30
+ ## 2. Check the environment first
31
+
32
+ ```bash
33
+ tmf doctor
34
+ ```
35
+
36
+ `doctor` reports *every* check instead of stopping at the first failure, split
37
+ into `required` (a missing one makes the exit code 1) and `optional` (reported
38
+ as a warning — an unavailable GPU backend is normal on a laptop). `tmf doctor
39
+ --json` gives the same result as machine-readable JSON, which is what CI and
40
+ the OpenClaw/Hermes adapters consume.
41
+
42
+ ```bash
43
+ tmf backends # which trainer backends exist and which are usable here
44
+ ```
45
+
46
+ ## 3. Create a project
47
+
48
+ ```bash
49
+ mkdir my-foundry && cd my-foundry
50
+ tmf init --count 160
51
+ ```
52
+
53
+ This writes `tmf.config.json` plus a synthetic corpus under `data/`. `init`
54
+ refuses to overwrite an existing config (exit code 1), so re-running it cannot
55
+ silently destroy your settings. To regenerate only the corpus later:
56
+
57
+ ```bash
58
+ tmf synth --out data --count 320
59
+ ```
60
+
61
+ ## 4. Validate the config before spending time on training
62
+
63
+ ```bash
64
+ tmf config validate
65
+ ```
66
+
67
+ Validation is exhaustive: you get one line per problem with the exact field
68
+ path (`train.mode`, `data.datasets[1].file`, …) rather than one error at a
69
+ time. The accepted `train.mode` values are constrained to what the selected
70
+ backend actually supports (`lora`, `pretrain`, `full-finetune`), so an
71
+ impossible run fails here instead of halfway through training.
72
+
73
+ ## 5. Train
74
+
75
+ ```bash
76
+ tmf train --job my-first-job
77
+ ```
78
+
79
+ The job runs as four durable steps — `data -> base -> train -> finalize` — and
80
+ each one is checkpointed. Useful properties:
81
+
82
+ - **Resumable.** Re-run the same `--job` id and finished steps are reused
83
+ instead of recomputed. `--no-resume` ignores previous state; a job an
84
+ operator cancelled needs the explicit `--resume-cancelled`.
85
+ - **Auditable.** Every step and training step appends to an audit log.
86
+ - **Honest about results.** The final manifest reports the parameter L2 delta,
87
+ so "it trained" is a measured claim, not a hope.
88
+
89
+ ### Default hyperparameters
90
+
91
+ `tmf init` writes these, and they are the ones the tests pin:
92
+
93
+ | key | default | why |
94
+ | --- | --- | --- |
95
+ | `steps` | `120` | enough to see the loss move on a first run; raise it for real jobs |
96
+ | `lr` | `0.005` | `0.05` oscillates on the builtin-js AdamW path and the holdout improvement disappears |
97
+ | `batchSize` | `4` | keeps a CPU-only run inside the default wall-clock budget |
98
+
99
+ Raising `lr` back toward `0.05` is the single most common way to make a run
100
+ look trained while the evaluation gates reject it.
101
+
102
+ ## 6. Inspect what happened
103
+
104
+ ```bash
105
+ tmf status my-first-job
106
+ ```
107
+
108
+ The state and audit trail are read back from disk, not from memory, so this
109
+ works from a new shell, after a reboot, or from another process. An unknown job
110
+ id exits 1.
111
+
112
+ ## 7. Evaluate on held-out data
113
+
114
+ Evaluation is deliberately a separate job from training: it loads the base and
115
+ adapter checkpoints from disk, scores both on a holdout split that is asserted
116
+ to be disjoint from training data, and only then decides whether an improvement
117
+ may be claimed at all. `verdict.improvementClaimAllowed` is false unless the
118
+ gates pass, and `assertDeliverable(report)` throws `EVAL_NOT_DELIVERABLE` on a
119
+ failed gate, so a regression cannot be exported as a win.
120
+
121
+ The evaluation job is available programmatically as `evalJob.runEvaluationJob`
122
+ (see `test/eval-job.test.mjs` for a complete worked example, including the
123
+ refusal path).
124
+
125
+ ## 8. Use it from code instead of the shell
126
+
127
+ The CLI is a thin wrapper over the programmatic API, so embedders get identical
128
+ behaviour without shelling out:
129
+
130
+ ```js
131
+ import { doctor, synthesize, train, status } from 'taskforce-model-foundry';
132
+
133
+ const health = await doctor({ baseDir: process.cwd() });
134
+ if (!health.ok) throw new Error('environment is not ready');
135
+
136
+ await synthesize({ baseDir: process.cwd(), outDir: 'data', taskCount: 160 });
137
+ const { job, artifacts } = await train({ baseDir: process.cwd(), jobId: 'from-code' });
138
+ console.log(job.state, artifacts.metrics.parameterL2Delta); // 'succeeded', e.g. 19.1
139
+
140
+ const st = await status({ baseDir: process.cwd(), jobId: 'from-code' });
141
+ console.log(st.found, st.state.state, st.audit.length);
142
+ ```
143
+
144
+ Lower-level building blocks are re-exported under stable namespaces —
145
+ `data`, `synth`, `jobs`, `trainJob`, `evalJob`, `gates`, `backends` — so you can
146
+ compose your own job without importing internal file paths.
147
+
148
+ ## 9. See the whole thing run
149
+
150
+ ```bash
151
+ # from an install (the script ships in the tarball)
152
+ bash node_modules/taskforce-model-foundry/scripts/e2e-demo.sh
153
+ TMF_DEMO_KEEP=1 bash node_modules/taskforce-model-foundry/scripts/e2e-demo.sh
154
+
155
+ # from a source checkout
156
+ npm run demo # bash scripts/e2e-demo.sh
157
+ TMF_DEMO_KEEP=1 npm run demo # keep the temp workdir to poke at the artifacts
158
+ ```
159
+
160
+ The demo runs in a throwaway directory and walks the full chain: version,
161
+ backends, init, config validate, doctor, train, status, and a resumed re-run.
162
+
163
+ ## 10. Full-parameter runs instead of LoRA
164
+
165
+ `mode` accepts exactly three values (`src/config.mjs`, `MODES`):
166
+
167
+ | mode | what it trains | checkpoint written under `<runRoot>/<jobId>/model/` |
168
+ | --- | --- | --- |
169
+ | `lora` | low-rank adapter on top of a frozen base | `adapter.json` |
170
+ | `pretrain` | all parameters, from the seeded init | `tuned.json` |
171
+ | `full-finetune` | all parameters, starting from the base checkpoint | `tuned.json` |
172
+
173
+ Backends advertise which modes they accept, and the train job refuses the rest
174
+ *before* spending a step:
175
+
176
+ | backend | modes |
177
+ | --- | --- |
178
+ | `builtin-js` | `pretrain`, `lora`, `full-finetune` |
179
+ | `hf-peft` | `lora`, `full-finetune` |
180
+
181
+ ```
182
+ $ tmf backends
183
+ ```
184
+
185
+ ### What `hf-peft` actually does, and what it does not
186
+
187
+ `hf-peft` runs `src/train/backends/hf_peft_runner.py` as a local subprocess
188
+ against a model already on disk. It is a local-execution backend: HF offline
189
+ mode is forced, so a missing local model fails instead of downloading one.
190
+ Capabilities are reported in three states, and the third state is never
191
+ dressed up as the first.
192
+
193
+ | capability | state | evidence / limit |
194
+ | --- | --- | --- |
195
+ | LoRA train on CPU, loss history, weight movement | measured | `scripts/hf-peft-e2e.mjs` reports `firstLoss`, `finalLoss` and a non-zero `parameterL2Delta` |
196
+ | `full-finetune` mode (all weights trainable) | measured | same script, `train_full_finetune` step |
197
+ | checkpoint save, reload, independent re-evaluation | measured | `saveModel` → `loadModel` → `evaluate` in a fresh process, `adapterLoaded: true` |
198
+ | baseline vs tuned evaluation | measured | two separate `evaluate()` processes, not two reads of one training log |
199
+ | greedy/sampled generation | measured | `generate()` returns the decoded continuation, same shape as `builtin-js` |
200
+ | resume from a trainer checkpoint | measured, step-coarse | resumes at the last `checkpoint-<step>` dir; steps after it are replayed, not recovered |
201
+ | cancellation | measured, destructive | `SIGKILL` to the worker. In-flight work is lost; only written checkpoints survive |
202
+ | memory bound (`maxMemoryMb`) | measured | `RLIMIT_AS` on the worker. Exceeding it terminates the process (`BACKEND_MEMORY_LIMIT`). A bound below the framework's own footprint fails at import, not mid-step — it is a cap, not a guarantee that a given job fits |
203
+ | CPU-seconds bound (`maxCpuSeconds`), thread pin | measured | `RLIMIT_CPU` and thread env pinning on the worker |
204
+ | step / wall-clock budget | measured, cooperative | checked between steps by a `Trainer` callback, never mid-kernel |
205
+ | export of an `hf-peft` adapter | measured | `exportModel()` now embeds the directory a pointer checkpoint references (`weights/<role>-weights/`, extension-filtered, depth-bounded, 512 MB cap) and hashes every embedded file into the manifest, so the bundle carries the adapter bytes. The *base* model is still referenced by `modelId`, not copied: a consumer needs the same local base model (`test/export.test.mjs`) |
206
+ | `fingerprint(handle)` (same contract as `builtin-js`) | measured | synchronous sha256 over the sorted weight/config files of the model and adapter dirs plus `modelId` and `mode`. Path-independent: moving a checkpoint dir keeps the digest, changing one weight byte changes it (`test/train-hf-peft.test.mjs`, runs without Python) |
207
+ | `train()` with in-memory `examples` (same parameter shape as `builtin-js`) | measured | the records are materialized to `train-examples.jsonl` under the run's `outDir`; `examplesFile` still works. Verified by `scripts/g12-contract-verify.mjs` (8 real CPU steps, non-zero `parameterL2Delta`) |
208
+ | `tmf train` job orchestration with `hf-peft` | measured | the tokenizer-ownership change landed: `capabilities.ownsTokenizer` plus `prepareDataset()` lets the job hand raw text to the Python worker instead of builtin token ids, so `train` -> `status` -> `evaluate` -> `export` all run on `hf-peft` from the CLI (`docs/reports/g12d-cli-e2e-evidence.json`) |
209
+ | operator cancel from the CLI (`Ctrl-C` / `SIGTERM`) | measured, cooperative at job-step granularity | `tmf train` installs SIGINT/SIGTERM handlers that abort the job's `AbortSignal`; the job finishes writing durable state, prints the completed steps and the exact `--resume-cancelled` command, and exits **130**. The signal is observed between job steps (and between training steps via the budget callback), so the step in flight is abandoned, not suspended. A second signal exits immediately and says so. Measured on jobs `g12d-cancel4` / `g12d-cancel5` (`docs/reports/g12d-cancel-resume-evidence.json`) |
210
+ | resume after cancel (`tmf train --resume-cancelled`) | measured, job-step granular | re-runs only the job steps that have no durable receipt. `g12d-cancel4` cancelled after `data`,`base` then resumed `train`,`finalize` to `succeeded` in 15s against ~40s for the same config cold. It is **not** training-step resume: a cancelled `train` step restarts from the last trainer checkpoint, and on this fixture 240 LoRA steps take 0.883s of wall clock while Python startup and model load dominate, so there is no practical window to land a signal inside the step loop |
211
+ | forced/immediate abort of a running job | **not supported** | cancellation is cooperative at the orchestration level. The CLI does `SIGKILL` the Python worker, but there is no guarantee of bounded-latency abort for an arbitrary backend step, and no rollback of partial writes beyond the durable step receipts |
212
+ | CUDA execution | **unverified** | the code path exists and `devices` reports `cuda` when torch sees it; this project has only exercised CPU |
213
+ | bf16 / fp16 precision | **not supported** | the runner trains in float32 only |
214
+ | filesystem / network isolation | **not supported** | `isolation: "process-rlimit"` bounds resources, it is not a sandbox |
215
+ | multi-GPU, distributed, or hosted training | **not supported** | out of scope: no paid compute, no egress |
216
+
217
+ Verify the claim rather than trusting the table:
218
+
219
+ ```bash
220
+ .tmf-venv/bin/python scripts/make-tiny-hf-fixture.py .tmf-run/fixtures/tiny-llama .tmf-run/fixtures/synth.jsonl
221
+ TMF_PYTHON=$PWD/.tmf-venv/bin/python node scripts/hf-peft-e2e.mjs
222
+ ```
223
+
224
+ The fixture is a randomly initialised 2-layer model with a word-level
225
+ tokenizer and synthetic data: no downloads, no accounts, no paid compute. When
226
+ the python stack or the fixture is absent, `test/train-hf-peft.test.mjs` skips
227
+ with the concrete reason instead of asserting against a mock.
228
+
229
+ Ask for a mode a backend does not support and the job fails fast with
230
+ `backend "<id>" does not support mode "<mode>"` (`src/jobs/train.mjs`), so a
231
+ typo costs you a second, not an afternoon.
232
+
233
+ To switch a project to a full fine-tune, change one field:
234
+
235
+ ```json
236
+ { "mode": "full-finetune" }
237
+ ```
238
+
239
+ Then re-run `tmf config validate` and `tmf train`. Two consequences worth
240
+ knowing before you do:
241
+
242
+ - The deliverable is a whole model (`model/tuned.json`), not a small adapter,
243
+ so exports are larger and no longer compose with a separately shipped base.
244
+ - `tmf evaluate` scores the tuned checkpoint instead of base+adapter; the
245
+ baseline comparison in the report is still the untouched base checkpoint, so
246
+ the gate still answers "did training help?".
247
+
248
+ ## 11. Exporting against a report you already reviewed
249
+
250
+ By default `tmf export` re-evaluates, because an export is gated on evaluation.
251
+ When a human has already read a report and signed off on the numbers, pin the
252
+ bundle to *that* report instead of to a fresh run:
253
+
254
+ ```
255
+ $ tmf export --job <jobId> --report .tmf-run/<jobId>/eval-report.json
256
+ ```
257
+
258
+ Both arguments matter. Reports live under `<runRoot>/<jobId>/`, and `runRoot`
259
+ defaults to `.tmf-run` (`src/config.mjs`), not `runs/`. Pass `--job` as well:
260
+ without it the job id falls back to the project directory name, and export
261
+ fails with `no durable job state for "<dirname>"` before it ever reads your
262
+ report. Note also that `tmf evaluate` exits 1 when the gates fail, yet it
263
+ still writes `eval-report.json` — a report on disk is evidence of a scored
264
+ run, not proof that it passed.
265
+
266
+ The supplied report has to prove it is the same file that was produced
267
+ (`assertReportIntegrity`, `src/jobs/evaluate.mjs`). Export refuses it otherwise:
268
+
269
+ | situation | error |
270
+ | --- | --- |
271
+ | not a JSON object | `eval report must be an object` |
272
+ | wrong/absent `format` | `eval report format mismatch: expected <format>, got <got>` |
273
+ | no `reportDigest` | `eval report is missing reportDigest` |
274
+ | contents edited after the fact | `eval report digest mismatch: file claims <a>, contents hash to <b>` |
275
+ | report belongs to another run | `eval report belongs to job <other>, not <jobId>` |
276
+
277
+ That last check is the one that matters in practice: it stops a bundle from
278
+ claiming the metrics of a different, better job. Editing a single number in the
279
+ report file — even a comment-like string — breaks the digest, so a pinned
280
+ export is only as good as the report nobody touched.
281
+
282
+ Programmatically the same path is `exportModel({ evalReport })`; passing
283
+ `evaluateIfMissing: false` with no report is an error rather than a silent
284
+ re-evaluation (`src/api.mjs`).
285
+
286
+ ## 12. Rolling back
287
+
288
+ Nothing here mutates a previous run. Every job owns an immutable directory
289
+ `<runRoot>/<jobId>/` holding its `model/`, its `eval-report.json`, its job
290
+ state and its audit events, and `tmf export` writes into
291
+ `<runRoot>/<jobId>/export/` unless you pass `--out`. Rolling back is therefore
292
+ re-pointing at an older job, not undoing a newer one.
293
+
294
+ 1. Find the job you want to go back to and confirm it is actually finished:
295
+
296
+ ```
297
+ $ tmf status <oldJobId>
298
+ ```
299
+
300
+ 2. Re-export it from its own reviewed report, so the bundle you ship is byte-
301
+ for-byte justified by the evaluation you trust:
302
+
303
+ ```
304
+ $ tmf export --job <oldJobId> --report .tmf-run/<oldJobId>/eval-report.json --out dist/rollback
305
+ ```
306
+
307
+ The digest and `lineage.jobId` checks from section 11 are what make this
308
+ safe: if you accidentally hand it the newer run's report, export fails
309
+ instead of producing a mislabelled bundle.
310
+
311
+ 3. Point the consumer at the rolled-back bundle. For the OpenClaw / Hermes
312
+ integrations that means the bundle path in the host config — see
313
+ [docs/integration.md](./integration.md); no state inside the toolkit needs
314
+ to be rewound.
315
+
316
+ To abandon a bad run rather than roll back to a good one, leave its directory
317
+ in place and stop referencing it. Deleting `<runRoot>/<jobId>/` is allowed but
318
+ destroys the audit trail for that job, and any bundle already exported from it
319
+ keeps its own copy of the report, so deletion is not a recall.
320
+
321
+ ## Troubleshooting
322
+
323
+ | Symptom | What it means |
324
+ | --- | --- |
325
+ | `tmf doctor` exits 1 with `node-version` | Node is older than 20; upgrade. |
326
+ | `tmf doctor` exits 1 with `trainer-backend` | No backend is usable here; `tmf backends` shows why. |
327
+ | `tmf init` exits 1 | A config already exists; edit it or pick another directory. |
328
+ | `tmf config validate` lists dataset problems | A `data.datasets[].file` path is missing — `tmf synth` regenerates the corpus. |
329
+ | `tmf status <id>` exits 1 | No job with that id in this project directory. |
330
+ | Exit code 2 from any command | Usage error (unknown command or flag); `tmf help` lists the surface. |
331
+
332
+ ## What is *not* in scope here
333
+
334
+ Private company data, paid training runs, publishing and production changes are
335
+ each separately authorized operations. This tutorial stays entirely on
336
+ self-generated synthetic data and local CPU training.