taskforce-model-foundry 0.1.0 → 0.3.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.
package/README.md CHANGED
@@ -22,8 +22,8 @@ node bin/tmf.mjs train -C /tmp/my-foundry --job first
22
22
  node bin/tmf.mjs status first -C /tmp/my-foundry
23
23
  ```
24
24
 
25
- This release is distributed as source on GitHub; an npm registry release has not
26
- been published. The built-in CPU backend needs no npm dependencies.
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
27
 
28
28
  See the full walkthrough in **[docs/tutorial.md](docs/tutorial.md)**, the host-side
29
29
  contract in **[docs/integration.md](docs/integration.md)**, or watch the
@@ -89,6 +89,24 @@ random-init local fixture (`docs/reports/g12d-cli-e2e-evidence.json`):
89
89
  `tmf evaluate` scores baseline and tuned in two independent processes (tuned
90
90
  holdout loss 3.9% better).
91
91
 
92
+ Long jobs can use `tmf train --background --job <id>` and
93
+ `tmf evaluate --background --job <id>`; each returns a request ID for
94
+ `train-status` / `evaluate-status`. Training also supports `train-cancel` and
95
+ explicit `--retry` after failure/interruption; `--resume-cancelled` resumes a
96
+ cancelled request as a new attempt. A job ID is bound to one training request:
97
+ changed config/device needs a new job ID. On Linux a user systemd unit
98
+ keeps the worker outside the calling CLI or Gateway process; a direct detached
99
+ fallback is reported as `restartDurable: false`. HF evaluation scores holdout,
100
+ generates predictions and scores validation in one model load per side.
101
+ The report records the actual evaluation device. See
102
+ [`docs/external-quality.md`](docs/external-quality.md) to require separate,
103
+ predeclared domain-quality gates before export.
104
+ `restartDurable: true` means isolated from a **Gateway process restart**, not
105
+ survival of a host reboot or power loss. HF `maxTokens` stops before the next
106
+ over-budget batch; after a hard-killed attempt, tokens spent since the last
107
+ durable training-step receipt cannot be reconstructed and must not be reported
108
+ as a verified cumulative total.
109
+
92
110
  Cancel and resume are stated at the precision the evidence supports.
93
111
  `Ctrl-C` or `SIGTERM` during `tmf train` aborts the job's `AbortSignal`: the
94
112
  job stops between steps, persists `cancelled` with the steps it did finish,
package/bin/tmf.mjs CHANGED
@@ -14,6 +14,8 @@ import {
14
14
  } from '../src/config.mjs';
15
15
  import { writeJson, readJson, exists } from '../src/core/fsx.mjs';
16
16
  import { VERSION } from '../src/index.mjs';
17
+ import { startBackgroundEvaluation, backgroundEvaluationStatus } from '../src/integrations/async-evaluate.mjs';
18
+ import { startBackgroundTraining, backgroundTrainingStatus, cancelBackgroundTraining } from '../src/integrations/async-train.mjs';
17
19
 
18
20
  const USAGE = `taskforce-model-foundry ${VERSION}
19
21
 
@@ -27,8 +29,12 @@ Commands:
27
29
  synth Generate a synthetic corpus (no private data needed)
28
30
  train Run a real post-training job
29
31
  evaluate Score a finished job on an independent holdout
32
+ train-status <job> <requestId> Read a background training receipt
33
+ evaluate-status <job> <requestId> Read a background evaluation receipt
34
+ train-cancel <job> <requestId> Cancel background training
30
35
  export Package a deliverable bundle (gated on evaluation)
31
36
  --report <file> reuses an existing eval report instead of re-evaluating
37
+ --quality-report <file> pins predeclared external quality evidence
32
38
  status <jobId> Show durable job state and recent audit events
33
39
  version Print the version
34
40
  help Print this help
@@ -42,6 +48,8 @@ Options:
42
48
  --count <n> Record count (synth/init, default: 160)
43
49
  --resume-cancelled Resume a job that an operator cancelled
44
50
  --no-resume Ignore existing job state instead of resuming
51
+ --background Run train/evaluate in an independent worker; return requestId
52
+ --retry Explicitly retry a failed/interrupted background request
45
53
 
46
54
  Exit codes:
47
55
  0 ok 1 the job ran and did not succeed 2 usage error
@@ -49,7 +57,7 @@ Exit codes:
49
57
  `;
50
58
 
51
59
  function parseArgs(argv) {
52
- const opts = { _: [], json: false, resume: true, resumeCancelled: false };
60
+ const opts = { _: [], json: false, resume: true, resumeCancelled: false, background: false, retry: false };
53
61
  for (let i = 0; i < argv.length; i += 1) {
54
62
  const arg = argv[i];
55
63
  const next = () => {
@@ -65,10 +73,13 @@ function parseArgs(argv) {
65
73
  case '--job': opts.job = next(); break;
66
74
  case '--out': opts.out = next(); break;
67
75
  case '--report': opts.report = next(); break;
76
+ case '--quality-report': opts.qualityReport = next(); break;
68
77
  case '--bundle-version': opts.bundleVersion = next(); break;
69
78
  case '--count': opts.count = Number(next()); break;
70
79
  case '--resume-cancelled': opts.resumeCancelled = true; break;
71
80
  case '--no-resume': opts.resume = false; break;
81
+ case '--background': opts.background = true; break;
82
+ case '--retry': opts.retry = true; break;
72
83
  case '-h': case '--help': opts.help = true; break;
73
84
  case '-v': case '--version': opts.version = true; break;
74
85
  default:
@@ -185,6 +196,16 @@ function installCancelHandlers(controller) {
185
196
 
186
197
  async function cmdTrain(opts, baseDir) {
187
198
  const { file, config } = await loadConfig({ file: opts.config ?? null, baseDir });
199
+ if (opts.background) {
200
+ if (!opts.job) throw new UsageError('background training requires --job <stable-id>');
201
+ if (!opts.resume) throw new UsageError('background training does not accept --no-resume');
202
+ const receipt = await startBackgroundTraining({
203
+ baseDir, configFile: file, jobId: opts.job, resumeCancelled: opts.resumeCancelled, retry: opts.retry,
204
+ });
205
+ out(opts, receipt, [`training request ${receipt.requestId}: ${receipt.state}`, `status: tmf train-status ${opts.job} ${receipt.requestId} --config ${file}`, `log: ${receipt.logFile ?? '(pending)'}`]);
206
+ return receipt.state === 'failed' ? 1 : 0;
207
+ }
208
+ if (opts.retry) throw new UsageError('--retry requires --background');
188
209
  const controller = new AbortController();
189
210
  const disarm = installCancelHandlers(controller);
190
211
  let job; let artifacts;
@@ -232,6 +253,15 @@ async function cmdTrain(opts, baseDir) {
232
253
 
233
254
  async function cmdEvaluate(opts, baseDir) {
234
255
  const { file, config } = await loadConfig({ file: opts.config ?? null, baseDir });
256
+ if (opts.background) {
257
+ if (!opts.job) throw new UsageError('background evaluation requires --job <stable-id>');
258
+ const receipt = await startBackgroundEvaluation({
259
+ baseDir, configFile: file, jobId: opts.job, reportFile: opts.report ?? null, retry: opts.retry,
260
+ });
261
+ out(opts, receipt, [`evaluation request ${receipt.requestId}: ${receipt.state}`, `status: tmf evaluate-status ${opts.job} ${receipt.requestId} --config ${file}`]);
262
+ return receipt.state === 'failed' ? 1 : 0;
263
+ }
264
+ if (opts.retry) throw new UsageError('--retry requires --background');
235
265
  const { artifacts, report } = await evaluate({
236
266
  config, baseDir, jobId: opts.job ?? null, reportFile: opts.report ?? null,
237
267
  });
@@ -270,6 +300,7 @@ async function cmdExport(opts, baseDir) {
270
300
  ({ bundle, report } = await exportModel({
271
301
  config, baseDir, jobId: opts.job ?? null, outDir: opts.out ?? null, version: opts.bundleVersion ?? null,
272
302
  evalReport, evaluateIfMissing: !evalReport,
303
+ qualityReport: opts.qualityReport ?? null,
273
304
  }));
274
305
  } catch (err) {
275
306
  // A blocked export is an expected outcome, not a crash: report the reason
@@ -308,6 +339,24 @@ async function cmdStatus(opts, baseDir, rest) {
308
339
  return 0;
309
340
  }
310
341
 
342
+ async function cmdBackgroundStatus(opts, baseDir, rest, kind) {
343
+ const [jobId, requestId] = rest;
344
+ if (!jobId || !requestId) throw new UsageError(`usage: tmf ${kind}-status <jobId> <requestId>`);
345
+ const receipt = kind === 'train'
346
+ ? await backgroundTrainingStatus({ baseDir, configFile: opts.config ?? null, jobId, requestId })
347
+ : await backgroundEvaluationStatus({ baseDir, configFile: opts.config ?? null, jobId, requestId });
348
+ out(opts, receipt, [`${kind} request ${requestId}: ${receipt.state}`, `status: ${receipt.statusFile}`, ...(receipt.logFile ? [`log: ${receipt.logFile}`] : [])]);
349
+ return ['failed', 'interrupted'].includes(receipt.state) ? 1 : 0;
350
+ }
351
+
352
+ async function cmdTrainCancel(opts, baseDir, rest) {
353
+ const [jobId, requestId] = rest;
354
+ if (!jobId || !requestId) throw new UsageError('usage: tmf train-cancel <jobId> <requestId>');
355
+ const receipt = await cancelBackgroundTraining({ baseDir, configFile: opts.config ?? null, jobId, requestId });
356
+ out(opts, receipt, [`training request ${requestId}: ${receipt.state}`]);
357
+ return 0;
358
+ }
359
+
311
360
  async function main(argv) {
312
361
  let opts;
313
362
  try {
@@ -333,6 +382,9 @@ async function main(argv) {
333
382
  case 'synth': return cmdSynth(opts, baseDir);
334
383
  case 'train': return cmdTrain(opts, baseDir);
335
384
  case 'evaluate': case 'eval': return cmdEvaluate(opts, baseDir);
385
+ case 'train-status': return cmdBackgroundStatus(opts, baseDir, rest, 'train');
386
+ case 'evaluate-status': return cmdBackgroundStatus(opts, baseDir, rest, 'evaluate');
387
+ case 'train-cancel': return cmdTrainCancel(opts, baseDir, rest);
336
388
  case 'export': return cmdExport(opts, baseDir);
337
389
  case 'status': return cmdStatus(opts, baseDir, rest);
338
390
  default:
@@ -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 any other domain-specific 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.
@@ -0,0 +1,59 @@
1
+ # External quality gates for domain-specific models
2
+
3
+ Foundry's independent loss/strict-match report is a **technical** gate, not a
4
+ domain-quality judgement. A project may require separately scored quality
5
+ evidence before export. Foundry does not ship domain datasets, scorers, judges,
6
+ rubrics or promotion thresholds. This mechanism does not run a scorer or claim
7
+ that a checksum proves the scores are truthful.
8
+
9
+ 1. **Before starting a new training job**, add `eval.externalQuality` to
10
+ `tmf.config.json`. Freeze the complete suite and scorer files; put their
11
+ SHA-256 digests in `suiteSha256` and `scorerSha256`. Declare nonempty gates
12
+ using the same `id`, `metric`, `comparator`, `threshold`, optional
13
+ `sampleMetric`/`minSamples` syntax as `eval.gates`. The training manifest
14
+ and job input digest pin this contract. Do not retrofit it onto an old job.
15
+ Optional `profile` names the project's protocol; optional `references` is a
16
+ map of project-defined names to SHA-256 digests (for example a baseline
17
+ output or rubric). Foundry stores them in the frozen contract without
18
+ interpreting their domain meaning.
19
+ 2. Evaluate the trained checkpoint with `tmf evaluate`. An external scorer can
20
+ call `qualityContext({configFile, jobId, evalReport})` to get the frozen
21
+ contract and checkpoint hash only after a passing technical report. Run the project's
22
+ independently maintained suite and scorer only after its protocol and
23
+ thresholds are frozen. Translate **all** required criteria into contract
24
+ gates before looking at candidate results. Foundry supplies no default
25
+ domain thresholds.
26
+ 3. The external scorer writes a JSON report with:
27
+
28
+ ```json
29
+ {
30
+ "format": "tmf.external-quality/v1",
31
+ "jobId": "new-training-job-id",
32
+ "suiteSha256": "<predeclared-suite-sha256>",
33
+ "scorerSha256": "<predeclared-scorer-sha256>",
34
+ "contractDigest": "<sha256Json(eval.externalQuality)>",
35
+ "checkpointSha256": "<sha256 of trained adapter or tuned checkpoint file>",
36
+ "evalReportDigest": "<technical eval reportDigest>",
37
+ "tunedFingerprint": "<technical eval lineage.tunedFingerprint>",
38
+ "metrics": { "quality": { "overall": 0.0 } },
39
+ "reportDigest": "<canonical digest of this report without reportDigest>"
40
+ }
41
+ ```
42
+
43
+ The scorer may import `externalQuality.sealExternalQualityEvidence` from
44
+ `taskforce-model-foundry` to compute the canonical `reportDigest`; the
45
+ `contractDigest` can be computed with
46
+ `externalQuality.externalQualityContractDigest(contract)`. These
47
+ digests detect edits and bind the evidence, but are **not signatures**.
48
+ Preserve the raw per-question outputs, blinded comparisons, scorer version
49
+ and human review provenance alongside the report.
50
+ 4. Export with `tmf export --job <id> --report <technical.json>
51
+ --quality-report <quality.json>`. Foundry checks the training-time contract,
52
+ both report digests, job ID, suite/scorer hashes, checkpoint pointer hash,
53
+ tuned weight fingerprint and every
54
+ external gate. Missing, stale, edited or failing evidence blocks export;
55
+ passing evidence is copied into the checksummed bundle.
56
+
57
+ An old job created without the external-quality contract cannot be promoted
58
+ retroactively; use a new job ID after freezing the contract. Keep each
59
+ domain-specific recipe in its own project, outside the generic Foundry package.
@@ -18,13 +18,13 @@ The package has **zero runtime dependencies** and needs Node.js >= 20
18
18
  network.
19
19
 
20
20
  ```bash
21
- # from a registry (once published)
21
+ # from the npm registry
22
22
  npm i taskforce-model-foundry
23
23
 
24
24
  # from a local tarball, which is how the install path was verified
25
- npm pack # -> taskforce-model-foundry-0.1.0.tgz
25
+ npm pack # -> taskforce-model-foundry-0.3.0.tgz
26
26
  cd /path/to/host
27
- npm i /path/to/taskforce-model-foundry-0.1.0.tgz
27
+ npm i /path/to/taskforce-model-foundry-0.3.0.tgz
28
28
  ```
29
29
 
30
30
  The install provides one bin, `tmf` (`node_modules/.bin/tmf`), and the
@@ -178,7 +178,7 @@ when no Python interpreter is on PATH).
178
178
 
179
179
  ## 4. Action and tool table
180
180
 
181
- Six actions, six tools, one table. `compute: true` means the call spends real
181
+ Nine actions, nine tools, one table. `compute: true` means the call spends real
182
182
  CPU time and writes run artifacts; those are the calls a host should gate.
183
183
 
184
184
  | OpenClaw action | Hermes tool | Compute | Required | Accepted params |
@@ -186,13 +186,16 @@ CPU time and writes run artifacts; those are the calls a host should gate.
186
186
  | `doctor` | `tmf_doctor` | no | — | `configFile`, `requireConfig` |
187
187
  | `status` | `tmf_status` | no | `jobId` | `jobId`, `configFile`, `auditTail` |
188
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` |
189
+ | `train` | `tmf_train` | yes | — | `configFile`, `jobId`, `resume`, `resumeCancelled`, `auditEveryStep`, `background`, `retry` |
190
+ | `train_status` | `tmf_train_status` | no | `jobId`, `requestId` | `configFile`, `jobId`, `requestId` |
191
+ | `train_cancel` | `tmf_train_cancel` | yes | `jobId`, `requestId` | `configFile`, `jobId`, `requestId` |
192
+ | `evaluate` | `tmf_evaluate` | yes | — | `configFile`, `jobId`, `gates`, `reportFile`, `maxNewTokens`, `background`, `retry` |
193
+ | `evaluate_status` | `tmf_evaluate_status` | no | `jobId`, `requestId` | `configFile`, `jobId`, `requestId` |
194
+ | `export` | `tmf_export` | yes | — | `configFile`, `jobId`, `evalReport`, `qualityReport`, `outDir`, `version`, `evaluateIfMissing` |
192
195
 
193
196
  **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
197
+ inspection while making compute impossible: the four read-only actions answer
198
+ normally, and all five compute actions are refused with
196
199
  `compute-not-authorized` *before* any handler runs — nothing is written, no
197
200
  partial job appears. Mount read-only wherever the host cannot itself vouch that
198
201
  training was authorized.
@@ -0,0 +1,24 @@
1
+ # v0.2.0 — HF/PEFT runtime and evaluation reliability
2
+
3
+ This release adds tested single-GPU HF/PEFT execution, checkpoint resume,
4
+ EOS-terminated supervised targets, batched evaluation, and correct adapter
5
+ lineage reporting. Background OpenClaw evaluation now uses attempt-bound
6
+ reports and an independent systemd user worker where available, so a stale
7
+ report cannot be mistaken for a new result. Reports record the actual
8
+ evaluation device.
9
+
10
+ Verification before publication:
11
+
12
+ - TinyLlama 1.1B LoRA training, independent evaluation, gated export, and
13
+ offline adapter reload were exercised on a single NVIDIA GB10.
14
+ - The repaired Gateway plugin completed a 1.1B background evaluation with
15
+ 4/4 prespecified technical gates passing.
16
+ - An eight-class public BANKING77 pilot reached 144/160 exact matches after
17
+ tuning versus 0/160 with the base model. This is not a full 77-class
18
+ benchmark or enterprise-data acceptance.
19
+ - Isolated tests exercised duplicate submissions, checkpoint recovery after
20
+ SIGKILL, corrupted inputs, simulated ENOSPC, and consecutive jobs.
21
+
22
+ Limits: live Gateway restart survival, real host power loss and physical disk
23
+ exhaustion were not measured. The public pilot does not establish full business
24
+ readiness, and no private production data is included in this release.
@@ -0,0 +1,28 @@
1
+ # v0.3.0 — durable workers and domain-neutral quality gates
2
+
3
+ This release makes long local training and evaluation jobs easier to supervise
4
+ without coupling Foundry to any one task domain.
5
+
6
+ - `tmf train/evaluate --background` return durable request IDs; status,
7
+ cancellation and explicit retry operations expose the worker lifecycle.
8
+ Linux systemd user units isolate workers from the calling CLI/Gateway process
9
+ where available. Direct-detached fallback reports its weaker durability.
10
+ - HF/PEFT evaluation now computes holdout loss, greedy predictions and
11
+ validation loss in one model load per side. Training token usage and
12
+ evaluation resource/device reporting now reflect work actually performed.
13
+ - Projects can freeze an external-quality contract before training and bind a
14
+ project-owned scorer report to the job, technical evaluation and checkpoint.
15
+ Failed or missing external gates block export. Domain suites, rubrics,
16
+ judges and thresholds are deliberately **not** included in Foundry.
17
+ - Model cards no longer imply that all non-synthetic project data is synthetic.
18
+
19
+ Verification: 244 Node tests passed with 0 failures/skips before release prep;
20
+ the same 31B smoke adapter's loss values and 40/40 prediction digests matched
21
+ the previous evaluation while wall time fell from 3487.742s to 1451.132s.
22
+ That smoke candidate still failed one of two predeclared technical gates and
23
+ was **not** exported or accepted as a quality improvement.
24
+
25
+ Limits: no physical power-loss or disk-exhaustion proof, no full business
26
+ benchmark result, and no domain-specific quality acceptance is claimed by
27
+ this release. A project-owned scorer must supply and substantiate its own
28
+ external evidence.
package/docs/tutorial.md CHANGED
@@ -222,9 +222,13 @@ TMF_PYTHON=$PWD/.tmf-venv/bin/python node scripts/hf-peft-e2e.mjs
222
222
  ```
223
223
 
224
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.
225
+ tokenizer and synthetic data: no downloads, no accounts, no paid compute.
226
+ When the Python stack is available, `test/train-hf-peft.test.mjs` builds a
227
+ missing fixture locally before running real backend tests. If the Python
228
+ dependencies are unavailable, those tests skip with the concrete reason
229
+ instead of asserting against a mock. The normal-path test memory budget is
230
+ 65536 MiB of virtual address space to allow CUDA-enabled PyTorch to import;
231
+ the 64 MiB failure-path test remains deliberately constrained.
228
232
 
229
233
  Ask for a mode a backend does not support and the job fails fast with
230
234
  `backend "<id>" does not support mode "<mode>"` (`src/jobs/train.mjs`), so a
@@ -1,5 +1,5 @@
1
1
  name: taskforce-model-foundry
2
- version: 0.1.0
2
+ version: 0.3.0
3
3
  description: Taskforce Model Foundry tools (synthesize, train, evaluate, export) for Hermes.
4
4
  author: Taskforce
5
5
  manifest_version: 2
@@ -20,7 +20,11 @@ export const PARAM_SCHEMA = {
20
20
  gates: { type: 'string', description: 'Evaluation gate expression.' },
21
21
  reportFile: { type: 'string', description: 'Where to write the evaluation report.' },
22
22
  maxNewTokens: { type: 'number', description: 'Generation budget per eval sample.' },
23
+ background: { type: 'boolean', description: 'Run training or evaluation in an independent worker and return a durable request id.' },
24
+ retry: { type: 'boolean', description: 'Retry the same failed or interrupted background request; never duplicates a running request.' },
25
+ requestId: { type: 'string', description: 'Background request id returned by tmf_train or tmf_evaluate.' },
23
26
  evalReport: { type: 'string', description: 'Evaluation report consumed by export.' },
27
+ qualityReport: { type: 'string', description: 'Predeclared external quality evidence report consumed by export.' },
24
28
  version: { type: 'string', description: 'Export version label.' },
25
29
  evaluateIfMissing: { type: 'boolean', description: 'Run evaluation when no report exists.' },
26
30
  };
@@ -2,7 +2,7 @@
2
2
  "id": "taskforce-model-foundry",
3
3
  "name": "Taskforce Model Foundry",
4
4
  "description": "Taskforce Model Foundry tools (contract v1).",
5
- "version": "0.1.0",
5
+ "version": "0.3.0",
6
6
  "configSchema": {
7
7
  "type": "object",
8
8
  "properties": {},
@@ -17,7 +17,10 @@
17
17
  "tmf_status",
18
18
  "tmf_synthesize",
19
19
  "tmf_train",
20
+ "tmf_train_status",
21
+ "tmf_train_cancel",
20
22
  "tmf_evaluate",
23
+ "tmf_evaluate_status",
21
24
  "tmf_export"
22
25
  ]
23
26
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "taskforce-model-foundry",
3
- "version": "0.1.0",
3
+ "version": "0.3.0",
4
4
  "description": "Taskforce Model Foundry: automated private-data model customization engine for OpenClaw and Hermes. Real post-training (weight/adapter updates), independent holdout evaluation, auditable jobs, and signed export lineage.",
5
5
  "type": "module",
6
6
  "license": "MIT",
package/src/api.mjs CHANGED
@@ -17,6 +17,8 @@ import { encodeRecords } from './train/dataset.mjs';
17
17
  import { exportModel as packageExport } from './export/package.mjs';
18
18
  import { exists, readJson, readJsonl } from './core/fsx.mjs';
19
19
  import { VERSION } from './version.mjs';
20
+ import { sha256Json, sha256File } from './core/hash.mjs';
21
+ import { verifyExternalQuality } from './eval/external-quality.mjs';
20
22
 
21
23
  export const PRODUCT = 'taskforce-model-foundry';
22
24
  const MIN_NODE_MAJOR = 20;
@@ -149,6 +151,7 @@ export async function train({
149
151
  modelConfig: resolved.model,
150
152
  hyper: resolved.hyper,
151
153
  trainBudget: resolved.trainBudget,
154
+ externalQuality: resolved.eval?.externalQuality ?? null,
152
155
  mode: resolved.mode,
153
156
  seed: resolved.seed,
154
157
  maxVocab: resolved.model.maxVocab,
@@ -221,7 +224,9 @@ async function resolveArtifacts({ artifacts, config, jobId }) {
221
224
  const result = Object.fromEntries((state.completedSteps ?? [])
222
225
  .filter((step) => step && typeof step === 'object' && step.name)
223
226
  .map((step) => [step.name, step.output]));
224
- return trainingArtifacts({ ...state, result });
227
+ // The finalize step is the durable manifest. It includes the predeclared
228
+ // external-quality contract, which is not a standalone step in the map.
229
+ return trainingArtifacts({ ...state, result: result.finalize ?? result });
225
230
  }
226
231
 
227
232
  /**
@@ -267,6 +272,7 @@ export async function evaluate({
267
272
  seed: resolved.seed,
268
273
  dataDir: resolvedArtifacts.dataDir,
269
274
  dataReportFile: resolvedArtifacts.dataReportFile ?? null,
275
+ externalQualityContractDigest: resolvedArtifacts.externalQuality ? sha256Json(resolvedArtifacts.externalQuality) : null,
270
276
  },
271
277
  reportFile: file,
272
278
  maxNewTokens,
@@ -292,6 +298,24 @@ async function readPinnedReport(file, baseDir) {
292
298
  return parsed.reportFile ? parsed : { ...parsed, reportFile: abs };
293
299
  }
294
300
 
301
+ /** Bind a project's external scorer to a successful technical evaluation. */
302
+ export async function qualityContext({ configFile = null, baseDir = process.cwd(), jobId, evalReport } = {}) {
303
+ const { config } = await loadConfig({ file: configFile, baseDir });
304
+ const artifacts = await resolveArtifacts({ config, jobId });
305
+ const technical = typeof evalReport === 'string' ? await readPinnedReport(evalReport, config.baseDir) : evalReport;
306
+ assertReportIntegrity(technical, { jobId: artifacts.jobId });
307
+ if (technical.verdict?.status !== 'passed' || !technical.verdict.deliveryEligible) {
308
+ throw new Error('external quality requires a passed technical evaluation');
309
+ }
310
+ const contract = config.eval?.externalQuality;
311
+ if (!contract || !artifacts.externalQuality || sha256Json(contract) !== sha256Json(artifacts.externalQuality) ||
312
+ technical.lineage?.externalQualityContractDigest !== sha256Json(contract)) {
313
+ throw new Error('external quality contract was not frozen into training and technical evaluation');
314
+ }
315
+ const checkpoint = artifacts.adapterCheckpoint ?? artifacts.tunedCheckpoint;
316
+ return { contract, jobId: artifacts.jobId, evalReport: technical, checkpointSha256: await sha256File(checkpoint) };
317
+ }
318
+
295
319
  /**
296
320
  * Package a deliverable bundle. The gate lives inside exportModel, so a
297
321
  * failed or baseline-only evaluation cannot produce an export.
@@ -303,6 +327,7 @@ export async function exportModel({
303
327
  jobId = null,
304
328
  artifacts = null,
305
329
  evalReport = null,
330
+ qualityReport = null,
306
331
  outDir = null,
307
332
  version = null,
308
333
  evaluateIfMissing = true,
@@ -325,14 +350,33 @@ export async function exportModel({
325
350
  assertReportIntegrity(report, { jobId });
326
351
  resolvedArtifacts = await resolveArtifacts({ artifacts, config: resolved, jobId });
327
352
  }
353
+ let externalQuality = null;
354
+ if (resolved.eval?.externalQuality) {
355
+ if (!resolvedArtifacts.externalQuality || sha256Json(resolvedArtifacts.externalQuality) !== sha256Json(resolved.eval.externalQuality)) {
356
+ throw new Error('external quality contract was not frozen into this training job; start a new job with the contract predeclared');
357
+ }
358
+ if (report.lineage?.externalQualityContractDigest !== sha256Json(resolved.eval.externalQuality)) {
359
+ throw new Error('technical evaluation is not bound to the predeclared external quality contract');
360
+ }
361
+ externalQuality = await verifyExternalQuality({
362
+ contract: resolved.eval.externalQuality,
363
+ evidence: qualityReport,
364
+ artifacts: resolvedArtifacts,
365
+ evalReport: report,
366
+ baseDir: resolved.baseDir,
367
+ });
368
+ } else if (qualityReport) {
369
+ throw new Error('qualityReport supplied but eval.externalQuality was not predeclared in the training config');
370
+ }
328
371
  const target = path.resolve(resolved.baseDir, outDir ?? path.join(resolved.runRootAbsolute, resolvedArtifacts.jobId, 'export'));
329
372
  const bundle = await packageExport({
330
373
  outDir: target,
331
374
  artifacts: resolvedArtifacts,
332
375
  evalReport: report,
376
+ externalQuality,
333
377
  config: resolved,
334
378
  name: resolved.project,
335
- version: version ?? '0.1.0',
379
+ version: version ?? VERSION,
336
380
  toolkitVersion: VERSION,
337
381
  });
338
382
  return { artifacts: resolvedArtifacts, report, bundle };