taskforce-model-foundry 0.0.0-stage → 0.2.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 (54) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/tmf.mjs +353 -0
  4. package/docs/acceptance/2026-11-22-hf-peft-public-pilot.md +75 -0
  5. package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
  6. package/docs/acceptance/r1-r7-reconciliation.md +185 -0
  7. package/docs/integration.md +228 -0
  8. package/docs/releases/v0.2.0.md +24 -0
  9. package/docs/tutorial.md +340 -0
  10. package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
  11. package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
  12. package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
  13. package/integrations/hermes-plugin/tests/test_register.py +230 -0
  14. package/integrations/openclaw-plugin/index.mjs +27 -0
  15. package/integrations/openclaw-plugin/tools.mjs +73 -0
  16. package/openclaw.plugin.json +25 -0
  17. package/package.json +70 -4
  18. package/scripts/e2e-demo.sh +56 -0
  19. package/src/api.mjs +341 -0
  20. package/src/config.mjs +342 -0
  21. package/src/core/autograd.mjs +451 -0
  22. package/src/core/fsx.mjs +65 -0
  23. package/src/core/hash.mjs +47 -0
  24. package/src/core/rng.mjs +70 -0
  25. package/src/data/clean.mjs +115 -0
  26. package/src/data/dedupe.mjs +125 -0
  27. package/src/data/ingest.mjs +184 -0
  28. package/src/data/pii.mjs +142 -0
  29. package/src/data/pipeline.mjs +183 -0
  30. package/src/data/provenance.mjs +88 -0
  31. package/src/data/split.mjs +193 -0
  32. package/src/data/synth.mjs +198 -0
  33. package/src/eval/evaluator.mjs +137 -0
  34. package/src/eval/gates.mjs +114 -0
  35. package/src/eval/metrics.mjs +90 -0
  36. package/src/export/package.mjs +365 -0
  37. package/src/index.mjs +26 -0
  38. package/src/integrations/async-evaluate-worker.mjs +39 -0
  39. package/src/integrations/async-evaluate.mjs +125 -0
  40. package/src/integrations/hermes.mjs +177 -0
  41. package/src/integrations/openclaw.mjs +164 -0
  42. package/src/jobs/evaluate.mjs +172 -0
  43. package/src/jobs/runner.mjs +323 -0
  44. package/src/jobs/train.mjs +303 -0
  45. package/src/model/lora.mjs +53 -0
  46. package/src/model/tokenizer.mjs +73 -0
  47. package/src/model/transformer.mjs +276 -0
  48. package/src/train/backends/builtin-js.mjs +367 -0
  49. package/src/train/backends/hf-peft.mjs +597 -0
  50. package/src/train/backends/hf_peft_runner.py +397 -0
  51. package/src/train/backends/index.mjs +92 -0
  52. package/src/train/dataset.mjs +56 -0
  53. package/src/train/optimizer.mjs +99 -0
  54. package/src/version.mjs +5 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Taskforce Model Foundry contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,134 @@
1
- # Temporary Holding Version
1
+ # taskforce-model-foundry
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ An automated model customization engine for OpenClaw and Hermes: it generates or
4
+ ingests a corpus, runs **real** post-training (weights actually move), evaluates
5
+ the result on an independent holdout split, and refuses to call a regression an
6
+ improvement.
7
+
8
+ - Node.js 20+, **zero runtime dependencies**
9
+ - Real training, not a simulation: every job reports its parameter L2 delta
10
+ - Durable, resumable, audited jobs — state is re-read from disk, not memory
11
+ - Gate-guarded evaluation: `assertDeliverable()` throws on a failed gate
12
+ - No private data and no network needed to try it out
13
+
14
+ ## Quickstart
15
+
16
+ ```bash
17
+ git clone https://github.com/ambitioncn/taskforce-model-foundry.git
18
+ cd taskforce-model-foundry
19
+ node bin/tmf.mjs --version
20
+ node bin/tmf.mjs init -C /tmp/my-foundry
21
+ node bin/tmf.mjs train -C /tmp/my-foundry --job first
22
+ node bin/tmf.mjs status first -C /tmp/my-foundry
23
+ ```
24
+
25
+ Versioned releases are available on GitHub and npm. The built-in CPU backend
26
+ needs no npm dependencies; HF/PEFT requires a separate Python environment.
27
+
28
+ See the full walkthrough in **[docs/tutorial.md](docs/tutorial.md)**, the host-side
29
+ contract in **[docs/integration.md](docs/integration.md)**, or watch the
30
+ whole chain run end to end:
31
+
32
+ ```bash
33
+ # from an install (the script ships in the tarball)
34
+ bash node_modules/taskforce-model-foundry/scripts/e2e-demo.sh
35
+
36
+ # from a source checkout
37
+ npm run demo # bash scripts/e2e-demo.sh
38
+ ```
39
+
40
+ The demo writes to a temporary workdir and removes it again, so it is safe to
41
+ run against an installed copy.
42
+
43
+ ## Programmatic API
44
+
45
+ ```js
46
+ import { doctor, synthesize, train, status } from 'taskforce-model-foundry';
47
+ ```
48
+
49
+ The CLI is a thin wrapper over this API, so embedders get identical behaviour
50
+ without shelling out. Lower-level building blocks are exported under the stable
51
+ namespaces `data`, `synth`, `jobs`, `trainJob`, `evalJob`, `gates`, `backends`.
52
+
53
+ ## CLI surface
54
+
55
+ | Command | Purpose |
56
+ | --- | --- |
57
+ | `tmf doctor` | Check environment, backends and config (`--json` for CI) |
58
+ | `tmf init` | Write a starter `tmf.config.json` plus synthetic data |
59
+ | `tmf config validate` | Report *every* config problem with its field path |
60
+ | `tmf backends` | List trainer backends and their availability |
61
+ | `tmf synth` | Generate a synthetic corpus |
62
+ | `tmf train` | Run a real post-training job (resumable, cancellable with `Ctrl-C`) |
63
+ | `tmf status <jobId>` | Durable job state and recent audit events |
64
+
65
+ Exit codes: `0` ok, `1` check/job failed, `2` usage error, `130` job cancelled
66
+ by an operator signal (durable state kept; the printed `--resume-cancelled`
67
+ command continues it).
68
+
69
+ Two trainer backends ship: `builtin-js` (pure JS, CPU, no extra deps) and
70
+ `hf-peft` (local transformers + PEFT subprocess, no downloads, no hosted API).
71
+ `hf-peft` train / checkpoint-reload / independent baseline-vs-tuned evaluation
72
+ / generation are exercised for real on CPU against a random-init local fixture
73
+ (`scripts/make-tiny-hf-fixture.py` + `scripts/hf-peft-e2e.mjs`); CUDA and
74
+ reduced precision are **not** verified here, and its per-worker RLIMIT bounds
75
+ are resource caps, not a sandbox. The capability table in
76
+ [docs/tutorial.md](docs/tutorial.md) marks each item measured, unverified or
77
+ not supported. `hf-peft` implements the same backend contract as `builtin-js`
78
+ (including `fingerprint()` and in-memory `examples`).
79
+
80
+ Tokenizer ownership is a backend capability, not a job assumption:
81
+ `capabilities.ownsTokenizer` plus `prepareDataset()` is the single place that
82
+ decides whether ids come from a vocabulary the job built from the data split
83
+ (`builtin-js`) or from the model's own tokenizer inside the Python worker
84
+ (`hf-peft`). Both the training job and the evaluation split loader go through
85
+ it, so `tmf train` is no longer builtin-only. Measured on CPU against the
86
+ random-init local fixture (`docs/reports/g12d-cli-e2e-evidence.json`):
87
+ `tmf train` succeeds (16 steps, loss 3.4277 -> 3.3744, parameter L2 delta
88
+ 0.652, step checkpoints written), `tmf status` reports the durable state, and
89
+ `tmf evaluate` scores baseline and tuned in two independent processes (tuned
90
+ holdout loss 3.9% better).
91
+
92
+ Cancel and resume are stated at the precision the evidence supports.
93
+ `Ctrl-C` or `SIGTERM` during `tmf train` aborts the job's `AbortSignal`: the
94
+ job stops between steps, persists `cancelled` with the steps it did finish,
95
+ prints the exact resume command and exits `130`; a second signal exits at once
96
+ and says the in-flight step is lost. `tmf train --resume-cancelled` then re-runs
97
+ only the steps without a durable receipt -- measured on job `g12d-cancel4`,
98
+ which cancelled after `data`,`base` and resumed `train`,`finalize` to
99
+ `succeeded` in 15s against ~40s cold
100
+ (`docs/reports/g12d-cancel-resume-evidence.json`). This is **job-step** resume,
101
+ not training-step resume: a cancelled `train` step restarts from the last
102
+ trainer checkpoint. Cancellation is **cooperative** -- the Python worker is
103
+ `SIGKILL`ed, but bounded-latency forced abort of an arbitrary backend step is
104
+ not offered, and there is no rollback beyond the step receipts.
105
+
106
+ Gate thresholds are project policy, declared under `eval.gates`, and the
107
+ built-in list is only the default. The defaults were calibrated against the
108
+ `builtin-js` demo, so a random-init tiny fixture cannot clear them -- the first
109
+ `hf-peft` export run stopped at `EXPORT_BLOCKED` with exact match 0 after 16
110
+ steps, which is the gate working rather than the export path failing. Declaring
111
+ `eval.gates` replaces the default list wholesale instead of merging it, because
112
+ a half-overridden gate set silently drops checks; an empty list, a duplicate
113
+ gate id, an unknown comparator and a `minSamples` without its `sampleMetric`
114
+ are all config errors reported by path. A project that narrows its gates is
115
+ stating, on the record, which quality bar its deliverable was actually held to.
116
+
117
+ `tmf doctor` grades an absent or unreadable config as a *warning* and still
118
+ exits `0`, so the environment and backend verdict survives a project that has
119
+ no config yet. Point it at the file with `--config <file>`, or use `tmf config
120
+ validate`, when CI must fail on a bad config.
121
+
122
+ ## Scope and authority
123
+
124
+ Synthetic data and local CPU training are the default. Real private company
125
+ data, paid training runs, production changes and publishing are each separately
126
+ authorized operations and are never performed implicitly.
127
+
128
+ ## Development
129
+
130
+ ```bash
131
+ npm test # the full suite
132
+ ```
133
+
134
+ MIT licensed.
package/bin/tmf.mjs ADDED
@@ -0,0 +1,353 @@
1
+ #!/usr/bin/env node
2
+ // The `tmf` command line.
3
+ //
4
+ // A thin, honest shell over src/api.mjs: it parses flags, prints human or JSON
5
+ // output, and maps outcomes to exit codes (0 ok, 1 failed check/invalid input,
6
+ // 2 usage error). It contains no training logic of its own.
7
+
8
+ import path from 'node:path';
9
+ import process from 'node:process';
10
+ import { doctor, synthesize, train, status, evaluate, exportModel } from '../src/api.mjs';
11
+ import {
12
+ loadConfig, validateConfig, exampleConfig, formatConfigErrors, ConfigError,
13
+ DEFAULT_CONFIG_FILES,
14
+ } from '../src/config.mjs';
15
+ import { writeJson, readJson, exists } from '../src/core/fsx.mjs';
16
+ import { VERSION } from '../src/index.mjs';
17
+
18
+ const USAGE = `taskforce-model-foundry ${VERSION}
19
+
20
+ Usage: tmf <command> [options]
21
+
22
+ Commands:
23
+ doctor Check environment, backends and config
24
+ init Write a starter tmf.config.json (+ synthetic data)
25
+ config validate [file] Validate a config file and print every problem
26
+ backends List trainer backends and availability
27
+ synth Generate a synthetic corpus (no private data needed)
28
+ train Run a real post-training job
29
+ evaluate Score a finished job on an independent holdout
30
+ export Package a deliverable bundle (gated on evaluation)
31
+ --report <file> reuses an existing eval report instead of re-evaluating
32
+ status <jobId> Show durable job state and recent audit events
33
+ version Print the version
34
+ help Print this help
35
+
36
+ Options:
37
+ -c, --config <file> Config file (default: ${DEFAULT_CONFIG_FILES.join(' or ')})
38
+ -C, --cwd <dir> Base directory (default: current directory)
39
+ --json Machine-readable JSON output
40
+ --job <id> Job id (train)
41
+ --out <dir> Output directory (synth/init, default: data)
42
+ --count <n> Record count (synth/init, default: 160)
43
+ --resume-cancelled Resume a job that an operator cancelled
44
+ --no-resume Ignore existing job state instead of resuming
45
+
46
+ Exit codes:
47
+ 0 ok 1 the job ran and did not succeed 2 usage error
48
+ 130 train was cancelled by SIGINT/SIGTERM (resume with --resume-cancelled)
49
+ `;
50
+
51
+ function parseArgs(argv) {
52
+ const opts = { _: [], json: false, resume: true, resumeCancelled: false };
53
+ for (let i = 0; i < argv.length; i += 1) {
54
+ const arg = argv[i];
55
+ const next = () => {
56
+ const value = argv[i + 1];
57
+ if (value === undefined || value.startsWith('-')) throw new UsageError(`${arg} requires a value`);
58
+ i += 1;
59
+ return value;
60
+ };
61
+ switch (arg) {
62
+ case '-c': case '--config': opts.config = next(); break;
63
+ case '-C': case '--cwd': opts.cwd = next(); break;
64
+ case '--json': opts.json = true; break;
65
+ case '--job': opts.job = next(); break;
66
+ case '--out': opts.out = next(); break;
67
+ case '--report': opts.report = next(); break;
68
+ case '--bundle-version': opts.bundleVersion = next(); break;
69
+ case '--count': opts.count = Number(next()); break;
70
+ case '--resume-cancelled': opts.resumeCancelled = true; break;
71
+ case '--no-resume': opts.resume = false; break;
72
+ case '-h': case '--help': opts.help = true; break;
73
+ case '-v': case '--version': opts.version = true; break;
74
+ default:
75
+ if (arg.startsWith('-')) throw new UsageError(`unknown option: ${arg}`);
76
+ opts._.push(arg);
77
+ }
78
+ }
79
+ return opts;
80
+ }
81
+
82
+ class UsageError extends Error {}
83
+
84
+ // Runner step records are objects; older state files may hold bare names.
85
+ function stepNames(steps) {
86
+ return (steps ?? []).map((step) => (typeof step === 'string' ? step : step?.name)).filter(Boolean);
87
+ }
88
+
89
+ function out(opts, payload, lines) {
90
+ if (opts.json) console.log(JSON.stringify(payload, null, 2));
91
+ else for (const line of lines) console.log(line);
92
+ }
93
+
94
+ async function cmdDoctor(opts, baseDir) {
95
+ const report = await doctor({ baseDir, configFile: opts.config ?? null, requireConfig: false });
96
+ out(opts, report, [
97
+ `tmf doctor — ${report.ok ? 'OK' : 'FAILED'}`,
98
+ `node ${report.node} on ${report.platform}`,
99
+ ...report.checks.map((c) => ` [${c.ok ? 'ok ' : c.level === 'required' ? 'FAIL' : 'warn'}] ${c.id}: ${c.detail}`),
100
+ ...(report.configErrors.length ? ['config problems:', formatConfigErrors(report.configErrors)] : []),
101
+ ]);
102
+ return report.ok ? 0 : 1;
103
+ }
104
+
105
+ async function cmdInit(opts, baseDir) {
106
+ const file = path.resolve(baseDir, opts.config ?? DEFAULT_CONFIG_FILES[0]);
107
+ if (await exists(file)) {
108
+ console.error(`refusing to overwrite existing config: ${file}`);
109
+ return 1;
110
+ }
111
+ const dataDir = opts.out ?? 'data';
112
+ const config = exampleConfig({ project: path.basename(baseDir), dataDir });
113
+ const corpus = await synthesize({ baseDir, outDir: dataDir, taskCount: opts.count ?? 160 });
114
+ config.data.datasets = Object.entries(corpus.files ?? {}).map(([name, p]) => ({
115
+ name,
116
+ path: path.relative(baseDir, p),
117
+ format: 'jsonl',
118
+ license: 'synthetic',
119
+ source: 'tmf synth',
120
+ }));
121
+ if (config.data.datasets.length === 0) config.data.datasets = exampleConfig({ dataDir }).data.datasets;
122
+ await writeJson(file, config);
123
+ out(opts, { configFile: file, datasets: config.data.datasets }, [
124
+ `wrote ${file}`,
125
+ `synthetic corpus in ${corpus.outDir}`,
126
+ 'next: tmf doctor, then tmf train',
127
+ ]);
128
+ return 0;
129
+ }
130
+
131
+ async function cmdConfig(opts, baseDir, rest) {
132
+ if (rest[0] !== 'validate') throw new UsageError('usage: tmf config validate [file]');
133
+ const file = rest[1] ?? opts.config ?? null;
134
+ try {
135
+ const loaded = await loadConfig({ file, baseDir });
136
+ out(opts, { ok: true, file: loaded.file, config: loaded.config }, [`config OK: ${loaded.file}`]);
137
+ return 0;
138
+ } catch (err) {
139
+ if (!(err instanceof ConfigError)) throw err;
140
+ out(opts, { ok: false, errors: err.errors, message: err.message }, [err.message, formatConfigErrors(err.errors)]);
141
+ return 1;
142
+ }
143
+ }
144
+
145
+ async function cmdBackends(opts) {
146
+ const report = await doctor({ baseDir: process.cwd() });
147
+ out(opts, report.backends, report.backends.map(
148
+ (b) => `${b.available ? 'available ' : 'unavailable'} ${b.id} modes=${(b.capabilities?.modes ?? []).join('|')}${b.available ? '' : ` (${b.reason})`}`,
149
+ ));
150
+ return report.backends.some((b) => b.available) ? 0 : 1;
151
+ }
152
+
153
+ async function cmdSynth(opts, baseDir) {
154
+ const corpus = await synthesize({ baseDir, outDir: opts.out ?? 'data', taskCount: opts.count ?? 160 });
155
+ out(opts, corpus, [`synthetic corpus written to ${corpus.outDir}`,
156
+ ...Object.entries(corpus.files ?? {}).map(([k, v]) => ` ${k}: ${v}`)]);
157
+ return 0;
158
+ }
159
+
160
+ // Operator cancellation from the shell. Node's default SIGINT handling would
161
+ // tear the process down mid-step and leave the job record saying `running`
162
+ // forever, so `train` installs its own handlers and turns the signal into the
163
+ // cooperative abort the runner already understands: the current step finishes
164
+ // or throws, state is persisted as `cancelled`, and the written checkpoints
165
+ // stay valid input for `--resume-cancelled`. A second signal is taken as "I
166
+ // meant now" and exits immediately, accepting the loss of the in-flight step.
167
+ function installCancelHandlers(controller) {
168
+ const signals = ['SIGINT', 'SIGTERM'];
169
+ let armed = true;
170
+ const handlers = signals.map((name) => {
171
+ const handler = () => {
172
+ if (!armed) {
173
+ console.error(`\n${name} again: exiting now, the in-flight step is lost`);
174
+ process.exit(130);
175
+ }
176
+ armed = false;
177
+ console.error(`\n${name} received: cancelling after the current step, checkpoints are kept`);
178
+ controller.abort(new Error(`operator cancelled with ${name}`));
179
+ };
180
+ process.on(name, handler);
181
+ return [name, handler];
182
+ });
183
+ return () => { for (const [name, handler] of handlers) process.off(name, handler); };
184
+ }
185
+
186
+ async function cmdTrain(opts, baseDir) {
187
+ const { file, config } = await loadConfig({ file: opts.config ?? null, baseDir });
188
+ const controller = new AbortController();
189
+ const disarm = installCancelHandlers(controller);
190
+ let job; let artifacts;
191
+ try {
192
+ ({ job, artifacts } = await train({
193
+ config, baseDir, jobId: opts.job ?? null, resume: opts.resume, resumeCancelled: opts.resumeCancelled,
194
+ signal: controller.signal,
195
+ }));
196
+ } catch (err) {
197
+ // The runner persists `cancelled` and then rethrows, so a cancellation
198
+ // arrives here as an exception even though the job record is intact. A
199
+ // stack trace would read like a crash; report the durable state instead.
200
+ if (err?.name !== 'JobCancelledError' && err?.code !== 'JOB_CANCELLED') throw err;
201
+ const jobId = opts.job ?? `train-${config.project}`;
202
+ const record = await status({ config, baseDir, jobId });
203
+ out(opts, { configFile: file, job: record.state, cancelled: true }, [
204
+ `job ${jobId}: ${record.state?.state ?? 'cancelled'}`,
205
+ `steps: ${stepNames(record.state?.completedSteps).join(' -> ') || '(none)'}`,
206
+ `cancelled: ${err.message}`,
207
+ `resume with: tmf train --config ${file} --job ${jobId} --resume-cancelled`,
208
+ ]);
209
+ return 130;
210
+ } finally {
211
+ disarm();
212
+ }
213
+ const ok = job.state === 'succeeded';
214
+ const cancelled = job.state === 'cancelled';
215
+ out(opts, { configFile: file, job, artifacts }, [
216
+ `job ${job.jobId}: ${job.state}`,
217
+ `steps: ${stepNames(job.completedSteps).join(' -> ') || '(none)'}`,
218
+ ...(ok ? [
219
+ `base checkpoint: ${artifacts.baseCheckpoint}`,
220
+ `${artifacts.adapterCheckpoint ? 'adapter' : 'tuned'} checkpoint: ${artifacts.adapterCheckpoint ?? artifacts.tunedCheckpoint}`,
221
+ `training steps: ${artifacts.metrics?.steps ?? '?'} parameter L2 delta: ${artifacts.metrics?.parameterL2Delta ?? '?'}`,
222
+ ] : cancelled ? [
223
+ `cancelled: ${job.error?.message ?? 'operator cancelled'}`,
224
+ `resume with: tmf train --config ${file} --job ${job.jobId} --resume-cancelled`,
225
+ ] : [`error: ${job.error?.message ?? 'see audit log'}`]),
226
+ ]);
227
+ // A cancelled job is not a failed check: 130 keeps it distinguishable from
228
+ // the exit 1 that means "the job ran and did not succeed".
229
+ if (cancelled) return 130;
230
+ return ok ? 0 : 1;
231
+ }
232
+
233
+ async function cmdEvaluate(opts, baseDir) {
234
+ const { file, config } = await loadConfig({ file: opts.config ?? null, baseDir });
235
+ const { artifacts, report } = await evaluate({
236
+ config, baseDir, jobId: opts.job ?? null, reportFile: opts.report ?? null,
237
+ });
238
+ const ok = report.verdict.status === 'passed';
239
+ out(opts, { configFile: file, artifacts, report }, [
240
+ `evaluation ${report.verdict.status}: ${report.verdict.summary}`,
241
+ `holdout records: ${report.inputs?.splits?.holdout ?? '?'} leakage: ${report.independence?.leaked?.length ?? 0}`,
242
+ ...report.gates.results.map((g) => ` [${g.ok ? 'ok ' : 'FAIL'}] ${g.id}: ${gateLine(g)}`),
243
+ `report: ${report.reportFile ?? '(not written)'}`,
244
+ ]);
245
+ return ok ? 0 : 1;
246
+ }
247
+
248
+ // Gate results carry `reason` only when they fail; a passing gate still needs a
249
+ // readable line, so restate the metric it cleared.
250
+ function gateLine(g) {
251
+ if (g.reason) return g.reason;
252
+ const comparator = { gte: '>=', lte: '<=', gt: '>', lt: '<' }[g.comparator] ?? g.comparator;
253
+ if (g.actual === null || g.actual === undefined) return `${g.metric} not measurable (needs ${comparator} ${g.threshold})`;
254
+ return `${g.metric}=${g.actual} meets ${comparator} ${g.threshold}`;
255
+ }
256
+
257
+ async function cmdExport(opts, baseDir) {
258
+ const { file, config } = await loadConfig({ file: opts.config ?? null, baseDir });
259
+ let bundle;
260
+ let report;
261
+ // --report pins the bundle to an existing report instead of re-evaluating,
262
+ // so the exported lineage carries the digest that was actually reviewed.
263
+ let evalReport = null;
264
+ if (opts.report) {
265
+ const reportFile = path.resolve(baseDir, opts.report);
266
+ if (!(await exists(reportFile))) throw new UsageError(`eval report not found: ${reportFile}`);
267
+ evalReport = await readJson(reportFile);
268
+ }
269
+ try {
270
+ ({ bundle, report } = await exportModel({
271
+ config, baseDir, jobId: opts.job ?? null, outDir: opts.out ?? null, version: opts.bundleVersion ?? null,
272
+ evalReport, evaluateIfMissing: !evalReport,
273
+ }));
274
+ } catch (err) {
275
+ // A blocked export is an expected outcome, not a crash: report the reason
276
+ // and the failed gates instead of a stack trace.
277
+ if (err?.code !== 'EXPORT_BLOCKED') throw err;
278
+ out(opts, { ok: false, code: err.code, reason: err.message, verdict: err.report?.verdict ?? null }, [
279
+ err.message,
280
+ ...(err.report?.gates?.results ?? []).filter((g) => !g.ok).map((g) => ` [FAIL] ${g.id}: ${gateLine(g)}`),
281
+ ]);
282
+ return 1;
283
+ }
284
+ out(opts, { configFile: file, bundle, verdict: report.verdict }, [
285
+ `exported ${bundle.manifest.name} ${bundle.manifest.version} (${bundle.manifest.kind})`,
286
+ `bundle: ${bundle.outDir}`,
287
+ `digest: ${bundle.bundleDigest}`,
288
+ `files: ${bundle.files.length} verify: sha256sum -c checksums.txt`,
289
+ ]);
290
+ return 0;
291
+ }
292
+
293
+ async function cmdStatus(opts, baseDir, rest) {
294
+ const jobId = rest[0] ?? opts.job;
295
+ if (!jobId) throw new UsageError('usage: tmf status <jobId>');
296
+ const { config } = await loadConfig({ file: opts.config ?? null, baseDir });
297
+ const report = await status({ config, baseDir, jobId });
298
+ if (!report.found) {
299
+ out(opts, report, [`job ${jobId}: not found`]);
300
+ return 1;
301
+ }
302
+ out(opts, report, [
303
+ `job ${jobId}: ${report.state.state} (attempt ${report.state.attempt ?? 1})`,
304
+ `steps: ${stepNames(report.state.completedSteps).join(' -> ') || '(none)'}`,
305
+ `audit events: ${report.auditCount}`,
306
+ ...report.audit.map((e) => ` ${e.at ?? ''} ${e.event}`),
307
+ ]);
308
+ return 0;
309
+ }
310
+
311
+ async function main(argv) {
312
+ let opts;
313
+ try {
314
+ opts = parseArgs(argv);
315
+ } catch (err) {
316
+ console.error(err.message);
317
+ console.error(USAGE);
318
+ return 2;
319
+ }
320
+ // `-h/--help` and `-v/--version` short-circuit before dispatch so that
321
+ // `tmf init --help` prints usage instead of actually writing files.
322
+ if (opts.help) { console.log(USAGE); return 0; }
323
+ if (opts.version) { console.log(VERSION); return 0; }
324
+ const [command = 'help', ...rest] = opts._;
325
+ const baseDir = path.resolve(opts.cwd ?? process.cwd());
326
+ switch (command) {
327
+ case 'help': console.log(USAGE); return 0;
328
+ case 'version': console.log(VERSION); return 0;
329
+ case 'doctor': return cmdDoctor(opts, baseDir);
330
+ case 'init': return cmdInit(opts, baseDir);
331
+ case 'config': return cmdConfig(opts, baseDir, rest);
332
+ case 'backends': return cmdBackends(opts);
333
+ case 'synth': return cmdSynth(opts, baseDir);
334
+ case 'train': return cmdTrain(opts, baseDir);
335
+ case 'evaluate': case 'eval': return cmdEvaluate(opts, baseDir);
336
+ case 'export': return cmdExport(opts, baseDir);
337
+ case 'status': return cmdStatus(opts, baseDir, rest);
338
+ default:
339
+ console.error(`unknown command: ${command}`);
340
+ console.error(USAGE);
341
+ return 2;
342
+ }
343
+ }
344
+
345
+ main(process.argv.slice(2)).then((code) => process.exit(code), (err) => {
346
+ if (err instanceof ConfigError) {
347
+ console.error(err.message);
348
+ console.error(formatConfigErrors(err.errors));
349
+ process.exit(1);
350
+ }
351
+ console.error(err?.stack ?? String(err));
352
+ process.exit(1);
353
+ });
@@ -0,0 +1,75 @@
1
+ # HF/PEFT repair and public-task pilot (2026-11-22)
2
+
3
+ This record covers the local TinyLlama 1.1B Chat (Apache-2.0) single-GPU LoRA
4
+ repair. It is **not** a production deployment or a full BANKING77 benchmark.
5
+ The source changes fix CUDA device selection, checkpoint-step resume, EOS
6
+ supervision, adapter/base lineage, one-load batch generation, device reporting,
7
+ and durable background evaluation attempts outside the Gateway cgroup when a
8
+ user systemd instance is available. Direct-launch fallback explicitly reports
9
+ `restartDurable=false`.
10
+
11
+ ## Public customer-support intent pilot
12
+
13
+ - Data: [PolyAI BANKING77](https://github.com/PolyAI-LDN/task-specific-datasets/tree/master/banking_data), CC BY 4.0. Official train/test CSV SHA-256:
14
+ `b06e26ac675513959a63135f11b94ea7786ed02da65db93a5650d8838cbc664b` /
15
+ `d12d6e3bc4c3103966ae786dc435913c0c563dfa328f5a3646d0e62cfeeb474d`.
16
+ - Before evaluating the model, choose the first eight alphabetically sorted
17
+ categories with at least 100 train examples: `Refund_not_showing_up`,
18
+ `activate_my_card`, `age_limit`, `apple_pay_or_google_pay`,
19
+ `automatic_top_up`, `balance_not_updated_after_bank_transfer`,
20
+ `balance_not_updated_after_cheque_or_cash_deposit`,
21
+ `beneficiary_not_allowed`. Per class, select 50 official-train and 20
22
+ official-test rows by ascending SHA-256 of query text. The official test
23
+ split is not used for training or model selection.
24
+ - One candidate: 300 steps, LoRA rank 8/alpha 16 on `q_proj,v_proj`, learning
25
+ rate 0.0002, batch size 1, CUDA float32, greedy generation. Foundry's
26
+ training-source dedupe reduced 400 rows to 223, then split them 156/34/33
27
+ for train/validation/holdout with zero measured cross-split leakage.
28
+ - Frozen pilot gates: official-test accuracy >=60%, absolute gain over the
29
+ unmodified base >=20 percentage points, strict one-field JSON >=90%.
30
+ Observed base **0/160**, tuned **144/160 (90%)**, JSON **160/160**.
31
+ Foundry's separately gated internal holdout was **29/33**, 4/4 technical
32
+ gates passed. Base model weight SHA-256 remained
33
+ `6e6001da2106d4757498752a021df6c2bdc332c650aae4bae6b0c004dcf14933`;
34
+ LoRA parameter L2 delta was 3.259838 and peak CUDA allocation 2434.503 MiB.
35
+ - General-regression screen: the first 40 ARC-Easy test items were
36
+ inconclusive (both models emitted invalid single-letter answers). A separate
37
+ 80-item set, fixed by ranks 41–120 of SHA-256-sorted test IDs, used
38
+ conditional answer-choice log likelihood. Base **15/80**, tuned **16/80**:
39
+ no >10-point regression on this small screen, but low absolute scores do
40
+ not certify broad ability. Five numeric-choice items required scoring their
41
+ actual multi-token labels rather than assuming all choices were A–D.
42
+ - The gated local adapter export passed all 11 manifest checksums; bundle
43
+ digest `e73a501f5dee33ccd81d1910a6e580adf9ff73d79043c612bbb9be6d2af2f967`.
44
+ Fresh offline processes loaded original and exported adapters and matched
45
+ generated token digests on 3/3 fixed prompts. The export still needs the
46
+ separately supplied base model; no weights or datasets are included here.
47
+
48
+ ## Isolated stability probes
49
+
50
+ Three sequential builtin-js jobs finished independently (`succeeded`, one
51
+ attempt each); replaying a finished ID did not rerun training. A separate HF
52
+ fixture job was killed with SIGKILL after a complete `checkpoint-50` appeared;
53
+ the original process exited -9 and a second attempt resumed from that exact
54
+ checkpoint to `succeeded`. Corrupt config/adapter files failed with nonzero
55
+ exit; a modified evaluation report was rejected by digest validation.
56
+ Targeted `ENOSPC` injection during an isolated job's data write produced
57
+ exit 1 and durable `failed` with error code `ENOSPC`, not a success receipt.
58
+ The OpenClaw background tool also demonstrated duplicate-request idempotency,
59
+ attempt-bound reports and explicit retry after interruption in the fixture
60
+ test and live plugin verification.
61
+
62
+ **Unverified boundaries:** actual host power loss, physical disk exhaustion,
63
+ running Gateway restart with a live worker, full 77-class BANKING77 quality,
64
+ and authorized de-identified enterprise data. SIGKILL and targeted `ENOSPC`
65
+ injection exercise failure paths, not those physical events. The public pilot
66
+ does not establish production or Chinese-screenplay-model quality.
67
+
68
+ For a local fixture regression run with a supported Python environment:
69
+
70
+ ```sh
71
+ TMF_PYTHON=/path/to/python TMF_DEVICE=cpu npm test
72
+ ```
73
+
74
+ When the full HF stack is present, the test builds its small random-init
75
+ fixture offline if missing; it never downloads pretrained weights.