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
@@ -0,0 +1,365 @@
1
+ // Export packaging: turn a succeeded training job plus an independent
2
+ // evaluation report into a single, self-describing, checksummed bundle.
3
+ //
4
+ // The gate is enforced here and not by the caller: `assertDeliverable` is the
5
+ // only door into `exportModel`, so a failed or baseline-only evaluation cannot
6
+ // be packaged at all. That is deliberate -- an export directory is the thing
7
+ // people copy around, and a bundle on disk is a claim of improvement.
8
+
9
+ import path from 'node:path';
10
+ import { copyFile, readFile, readdir } from 'node:fs/promises';
11
+ import { ensureDir, writeJson, writeFileAtomic, exists } from '../core/fsx.mjs';
12
+ import { sha256File, sha256Json, stableStringify } from '../core/hash.mjs';
13
+
14
+ export const EXPORT_FORMAT = 'tmf.export/v1';
15
+
16
+ export class ExportBlockedError extends Error {
17
+ constructor(message, { status = null, failed = [] } = {}) {
18
+ super(message);
19
+ this.name = 'ExportBlockedError';
20
+ this.code = 'EXPORT_BLOCKED';
21
+ this.status = status;
22
+ this.failed = failed;
23
+ }
24
+ }
25
+
26
+ /**
27
+ * Terminal check that an evaluation report authorises delivery.
28
+ *
29
+ * Throws `ExportBlockedError` for anything that is not an explicitly passed
30
+ * gated evaluation -- missing report, baseline-only run, failed gates, or a
31
+ * report whose verdict and gate block disagree.
32
+ */
33
+ export function assertDeliverable(report) {
34
+ if (!report || typeof report !== 'object') {
35
+ throw new ExportBlockedError('export requires an evaluation report', { status: 'missing' });
36
+ }
37
+ const status = report.verdict?.status ?? null;
38
+ const gatesPassed = report.gates?.passed === true;
39
+ const eligible = report.verdict?.deliveryEligible === true;
40
+ if (status !== 'passed' || !gatesPassed || !eligible) {
41
+ const failed = (report.gates?.failed ?? []).map((f) => f.id ?? f.metric ?? 'gate');
42
+ throw new ExportBlockedError(
43
+ `export blocked: evaluation status is ${status ?? 'unknown'}${failed.length ? ` (failed gates: ${failed.join(', ')})` : ''}`,
44
+ { status, failed },
45
+ );
46
+ }
47
+ return report;
48
+ }
49
+
50
+ function metricSummary(report) {
51
+ const m = report.metrics ?? {};
52
+ return {
53
+ holdoutLoss: m.tuned?.holdout?.loss ?? null,
54
+ baselineHoldoutLoss: m.baseline?.holdout?.loss ?? null,
55
+ holdoutLossRelativeImprovement: m.improvement?.holdoutLossRelative ?? null,
56
+ exactMatch: m.tuned?.holdout?.exactMatch?.accuracy ?? null,
57
+ exactMatchAbsoluteImprovement: m.improvement?.exactMatchAbsolute ?? null,
58
+ validationLossRelativeImprovement: m.improvement?.validationLossRelative ?? null,
59
+ };
60
+ }
61
+
62
+ function renderModelCard({ name, version, createdAt, report, artifacts, config, files }) {
63
+ const s = metricSummary(report);
64
+ const num = (v) => (typeof v === 'number' ? v.toFixed(6) : 'n/a');
65
+ const pct = (v) => (typeof v === 'number' ? `${(v * 100).toFixed(2)}%` : 'n/a');
66
+ const gateRows = (report.gates?.results ?? [])
67
+ .map((r) => `| ${r.id} | ${r.metric} | ${r.comparator ?? ''} ${r.threshold} | ${num(r.value)} | ${r.passed ? 'pass' : 'FAIL'} |`)
68
+ .join('\n');
69
+ return `# Model card: ${name} ${version}
70
+
71
+ Exported ${createdAt} by taskforce-model-foundry.
72
+
73
+ ## What this is
74
+
75
+ A small post-trained model produced from **synthetic data generated by this
76
+ toolkit**. It is a demonstration-scale artifact: it is not trained on real
77
+ enterprise data, and it carries no claim of fitness for production use.
78
+
79
+ - Mode: \`${config?.mode ?? artifacts?.metrics?.mode ?? 'unknown'}\`
80
+ - Backend: \`${report.backend?.id ?? 'unknown'}\`
81
+ - Base checkpoint: \`${path.basename(artifacts?.baseCheckpoint ?? 'n/a')}\`
82
+ - Delivered weights: \`${path.basename(artifacts?.adapterCheckpoint ?? artifacts?.tunedCheckpoint ?? 'n/a')}\`${artifacts?.adapterCheckpoint ? ' (adapter; requires the base checkpoint)' : ''}
83
+
84
+ ## Measured results
85
+
86
+ Measured on an independent holdout split that training never saw
87
+ (independence: \`${report.independence?.verdict ?? report.independence?.status ?? 'see eval-report.json'}\`).
88
+
89
+ | metric | value |
90
+ | --- | --- |
91
+ | holdout loss (tuned) | ${num(s.holdoutLoss)} |
92
+ | holdout loss (baseline) | ${num(s.baselineHoldoutLoss)} |
93
+ | holdout loss improvement | ${pct(s.holdoutLossRelativeImprovement)} |
94
+ | exact match (tuned) | ${pct(s.exactMatch)} |
95
+ | exact match improvement | ${pct(s.exactMatchAbsoluteImprovement)} |
96
+
97
+ ## Gates
98
+
99
+ | gate | metric | threshold | value | verdict |
100
+ | --- | --- | --- | --- | --- |
101
+ ${gateRows || '| (none recorded) | | | | |'}
102
+
103
+ Verdict: **${report.verdict?.status}** — ${report.verdict?.summary ?? ''}
104
+
105
+ ## Training data
106
+
107
+ Synthetic, generated locally. See \`data-report.json\` for the record counts,
108
+ dedupe and PII-scan results, and split digests.
109
+
110
+ ## Limitations and intended use
111
+
112
+ - Demonstration and integration testing only.
113
+ - Synthetic task distribution; behaviour outside it is unmeasured.
114
+ - No safety tuning, no real-world evaluation, no production authorisation.
115
+
116
+ ## Reproduce and roll back
117
+
118
+ See \`inference.md\`.
119
+
120
+ ## Files
121
+
122
+ ${files.map((f) => `- \`${f.path}\` (sha256 \`${f.sha256.slice(0, 16)}…\`)`).join('\n')}
123
+ `;
124
+ }
125
+
126
+ function renderInferenceDoc({ name, version, artifacts, config }) {
127
+ const adapter = artifacts?.adapterCheckpoint;
128
+ return `# Reproducible inference and rollback — ${name} ${version}
129
+
130
+ ## Verify the bundle first
131
+
132
+ \`\`\`bash
133
+ sha256sum -c checksums.txt
134
+ \`\`\`
135
+
136
+ Every file listed in \`manifest.json\` is covered. A checksum mismatch means the
137
+ bundle was modified after export: do not load it.
138
+
139
+ ## Load and run
140
+
141
+ \`\`\`js
142
+ import { backends } from 'taskforce-model-foundry';
143
+
144
+ const backend = await backends.resolveBackend('${config?.backend ?? 'builtin-js'}');
145
+ const handle = await backend.loadModel({
146
+ file: 'weights/base.json',${adapter ? "\n attachAdapter: 'weights/adapter.json'," : ''}
147
+ });
148
+ const out = await backend.generate({ handle, prompt: '<your prompt>', maxNewTokens: 34 });
149
+ \`\`\`
150
+
151
+ Generation defaults to temperature 0 (greedy) and is deterministic, so the same prompt and the
152
+ same checkpoint files reproduce the same completion. The metrics in
153
+ \`model-card.md\` were produced by exactly this path; re-running the evaluation
154
+ against \`eval-report.json\`'s lineage digests should reproduce them.
155
+
156
+ ## Roll back
157
+
158
+ ${adapter
159
+ ? `This export is an **adapter**. To roll back, stop loading
160
+ \`weights/adapter.json\` and serve \`weights/base.json\` alone — the base weights
161
+ are byte-identical to the pre-training checkpoint (see \`lineage.baseCheckpoint\`
162
+ in \`manifest.json\`), so rollback needs no retraining and no other artifact.`
163
+ : `This export is a **full tuned checkpoint**. To roll back, serve
164
+ \`weights/base.json\`, which is the pre-training checkpoint shipped in this same
165
+ bundle for exactly that purpose.`}
166
+
167
+ Rollback is complete when the served checksum matches \`weights/base.json\` in
168
+ \`checksums.txt\`.
169
+ `;
170
+ }
171
+
172
+ /**
173
+ * Package a succeeded training job into `outDir`.
174
+ *
175
+ * Requires an evaluation report that passed its gates; see `assertDeliverable`.
176
+ * Returns the manifest, the per-file checksums, and a bundle digest.
177
+ */
178
+
179
+ // Depth-bounded, extension-filtered copy of a weight directory into the bundle.
180
+ // The same filter the `hf-peft` fingerprint uses, so what gets embedded is what
181
+ // identifies the checkpoint.
182
+ const EMBED_EXTENSIONS = ['.safetensors', '.bin', '.pt', '.json', '.model', '.txt'];
183
+ const EMBED_MAX_DEPTH = 3;
184
+ const EMBED_MAX_BYTES = 512 * 1024 * 1024;
185
+
186
+ async function copyWeightTree(from, to, { depth = 0, budget } = {}) {
187
+ const copied = [];
188
+ let entries;
189
+ try {
190
+ entries = await readdir(from, { withFileTypes: true });
191
+ } catch {
192
+ return copied;
193
+ }
194
+ for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
195
+ const src = path.join(from, entry.name);
196
+ if (entry.isDirectory()) {
197
+ if (depth >= EMBED_MAX_DEPTH) continue;
198
+ const nested = await copyWeightTree(src, path.join(to, entry.name), { depth: depth + 1, budget });
199
+ for (const rel of nested) copied.push(path.join(entry.name, rel));
200
+ continue;
201
+ }
202
+ if (!entry.isFile()) continue;
203
+ if (!EMBED_EXTENSIONS.includes(path.extname(entry.name))) continue;
204
+ const buf = await readFile(src);
205
+ budget.bytes += buf.length;
206
+ if (budget.bytes > EMBED_MAX_BYTES) {
207
+ throw new Error(`exportModel: embedded weights exceed the ${EMBED_MAX_BYTES} byte bundle limit`);
208
+ }
209
+ await ensureDir(to);
210
+ await writeFileAtomic(path.join(to, entry.name), buf);
211
+ copied.push(entry.name);
212
+ }
213
+ return copied;
214
+ }
215
+
216
+ async function embedExternalWeights({ pointerFile, root, role }) {
217
+ let payload;
218
+ try {
219
+ payload = JSON.parse(await readFile(pointerFile, 'utf8'));
220
+ } catch {
221
+ // Not a JSON pointer (or not readable as one): nothing to embed.
222
+ return [];
223
+ }
224
+ if (payload?.format !== 'tmf-checkpoint-v1') return [];
225
+ const dir = payload.adapterDir ?? payload.dir ?? null;
226
+ if (!dir || !(await exists(dir))) return [];
227
+ const rel = `weights/${role}-weights`;
228
+ const budget = { bytes: 0 };
229
+ const copied = await copyWeightTree(dir, path.join(root, rel), { budget });
230
+ const files = [];
231
+ for (const name of copied) {
232
+ const to = `${rel}/${name.split(path.sep).join('/')}`;
233
+ files.push({
234
+ path: to,
235
+ role: `${role}-weights`,
236
+ sha256: await sha256File(path.join(root, to)),
237
+ source: path.join(dir, name),
238
+ });
239
+ }
240
+ return files;
241
+ }
242
+
243
+ export async function exportModel({
244
+ outDir,
245
+ artifacts,
246
+ evalReport,
247
+ config = null,
248
+ name = config?.project ?? 'taskforce-model',
249
+ version = '0.2.0',
250
+ toolkitVersion = null,
251
+ clock = () => new Date().toISOString(),
252
+ }) {
253
+ if (!outDir) throw new Error('exportModel requires outDir');
254
+ if (!artifacts?.baseCheckpoint) throw new Error('exportModel requires training artifacts with a baseCheckpoint');
255
+ assertDeliverable(evalReport);
256
+
257
+ const createdAt = clock();
258
+ const root = path.resolve(outDir);
259
+ await ensureDir(path.join(root, 'weights'));
260
+
261
+ const copies = [
262
+ { from: artifacts.baseCheckpoint, to: 'weights/base.json', role: 'base' },
263
+ artifacts.adapterCheckpoint ? { from: artifacts.adapterCheckpoint, to: 'weights/adapter.json', role: 'adapter' } : null,
264
+ artifacts.tunedCheckpoint ? { from: artifacts.tunedCheckpoint, to: 'weights/tuned.json', role: 'tuned' } : null,
265
+ artifacts.dataReportFile ? { from: artifacts.dataReportFile, to: 'data-report.json', role: 'data-report' } : null,
266
+ evalReport.reportFile ? { from: evalReport.reportFile, to: 'eval-report.json', role: 'eval-report' } : null,
267
+ ].filter(Boolean);
268
+
269
+ const files = [];
270
+ for (const copy of copies) {
271
+ if (!(await exists(copy.from))) throw new Error(`exportModel: missing input ${copy.role}: ${copy.from}`);
272
+ const dest = path.join(root, copy.to);
273
+ await copyFile(copy.from, dest);
274
+ files.push({ path: copy.to, role: copy.role, sha256: await sha256File(dest), source: copy.from });
275
+ }
276
+ // A `hf-peft` checkpoint file is a *pointer*: it names a local model dir and
277
+ // an adapter dir rather than carrying weights. Copying only the pointer would
278
+ // produce a package that cannot be reloaded anywhere else, so the referenced
279
+ // weight directory is embedded next to it and every embedded file is hashed
280
+ // into the manifest. Builtin-js checkpoints carry their own weights and are
281
+ // untouched by this.
282
+ for (const copy of copies) {
283
+ if (!copy.to.startsWith('weights/')) continue;
284
+ const embedded = await embedExternalWeights({ pointerFile: copy.from, root, role: copy.role });
285
+ for (const entry of embedded) files.push(entry);
286
+ }
287
+ if (!evalReport.reportFile) {
288
+ const dest = path.join(root, 'eval-report.json');
289
+ await writeJson(dest, evalReport);
290
+ files.push({ path: 'eval-report.json', role: 'eval-report', sha256: await sha256File(dest), source: 'inline' });
291
+ }
292
+
293
+ const lineage = {
294
+ data: {
295
+ dataDir: artifacts.dataDir ?? null,
296
+ reportFile: artifacts.dataReportFile ?? null,
297
+ splits: evalReport.inputs?.splits ?? null,
298
+ datasets: config?.data?.datasets ?? null,
299
+ synthetic: true,
300
+ },
301
+ parameters: {
302
+ mode: config?.mode ?? null,
303
+ seed: config?.seed ?? null,
304
+ model: config?.model ?? null,
305
+ hyper: config?.hyper ?? null,
306
+ trainBudget: config?.trainBudget ?? null,
307
+ },
308
+ training: {
309
+ jobId: artifacts.jobId ?? null,
310
+ metrics: artifacts.metrics ?? null,
311
+ },
312
+ evaluation: {
313
+ jobId: evalReport.jobId ?? null,
314
+ reportDigest: evalReport.reportDigest ?? null,
315
+ independence: evalReport.independence ?? null,
316
+ gates: evalReport.gates?.results ?? [],
317
+ lineage: evalReport.lineage ?? null,
318
+ },
319
+ baseCheckpoint: files.find((f) => f.role === 'base')?.sha256 ?? null,
320
+ };
321
+
322
+ const manifest = {
323
+ format: EXPORT_FORMAT,
324
+ name,
325
+ version,
326
+ createdAt,
327
+ toolkit: { name: 'taskforce-model-foundry', version: toolkitVersion },
328
+ kind: artifacts.adapterCheckpoint ? 'adapter' : 'full',
329
+ backend: evalReport.backend ?? null,
330
+ metrics: metricSummary(evalReport),
331
+ verdict: evalReport.verdict ?? null,
332
+ lineage,
333
+ files,
334
+ rollback: artifacts.adapterCheckpoint
335
+ ? 'serve weights/base.json alone; the adapter is additive and removing it restores pre-training behaviour'
336
+ : 'serve weights/base.json, the pre-training checkpoint shipped in this bundle',
337
+ docs: ['model-card.md', 'inference.md'],
338
+ };
339
+
340
+ const card = renderModelCard({ name, version, createdAt, report: evalReport, artifacts, config, files });
341
+ await writeFileAtomic(path.join(root, 'model-card.md'), card);
342
+ const inference = renderInferenceDoc({ name, version, artifacts, config });
343
+ await writeFileAtomic(path.join(root, 'inference.md'), inference);
344
+
345
+ for (const doc of ['model-card.md', 'inference.md']) {
346
+ files.push({ path: doc, role: 'doc', sha256: await sha256File(path.join(root, doc)), source: 'generated' });
347
+ }
348
+
349
+ manifest.bundleDigest = sha256Json(files.map((f) => [f.path, f.sha256]));
350
+ const manifestFile = path.join(root, 'manifest.json');
351
+ await writeJson(manifestFile, manifest);
352
+
353
+ const checksums = `${files.map((f) => `${f.sha256} ${f.path}`).join('\n')}\n${await sha256File(manifestFile)} manifest.json\n`;
354
+ await writeFileAtomic(path.join(root, 'checksums.txt'), checksums);
355
+
356
+ return {
357
+ outDir: root,
358
+ manifestFile,
359
+ manifest,
360
+ files,
361
+ bundleDigest: manifest.bundleDigest,
362
+ checksumsFile: path.join(root, 'checksums.txt'),
363
+ stable: stableStringify({ digest: manifest.bundleDigest }),
364
+ };
365
+ }
package/src/index.mjs ADDED
@@ -0,0 +1,26 @@
1
+ // Package entry point: the stable public surface.
2
+ //
3
+ // High-level operations come from ./api.mjs; the lower-level building blocks
4
+ // are re-exported under namespaces so embedders can compose their own jobs
5
+ // without reaching into file paths that may move.
6
+
7
+ export { PRODUCT, doctor, synthesize, train, status, evaluate } from './api.mjs';
8
+ export { exportModel as exportBundle } from './api.mjs';
9
+ export {
10
+ CONFIG_FORMAT, CONFIG_DEFAULTS, validateConfig, loadConfig, findConfigFile,
11
+ exampleConfig, formatConfigErrors, ConfigError,
12
+ } from './config.mjs';
13
+
14
+ export * as data from './data/pipeline.mjs';
15
+ export * as synth from './data/synth.mjs';
16
+ export * as jobs from './jobs/runner.mjs';
17
+ export * as trainJob from './jobs/train.mjs';
18
+ export * as evalJob from './jobs/evaluate.mjs';
19
+ export * as gates from './eval/gates.mjs';
20
+ export * as backends from './train/backends/index.mjs';
21
+ export * as exporter from './export/package.mjs';
22
+ export { exportModel, assertDeliverable, ExportBlockedError, EXPORT_FORMAT } from './export/package.mjs';
23
+
24
+ export { VERSION } from './version.mjs';
25
+ export * as openclaw from './integrations/openclaw.mjs';
26
+ export * as hermes from './integrations/hermes.mjs';
@@ -0,0 +1,39 @@
1
+ import { readJson, writeJson } from '../core/fsx.mjs';
2
+ import { sha256File, sha256Json } from '../core/hash.mjs';
3
+ import { evaluate } from '../api.mjs';
4
+ import path from 'node:path';
5
+
6
+ const [, , requestFile, statusFile] = process.argv;
7
+ if (!requestFile || !statusFile) throw new Error('worker requires request and status files');
8
+ const request = await readJson(requestFile);
9
+ const old = await readJson(statusFile);
10
+ if (old.requestId !== request.requestId || old.attempt !== request.attempt) {
11
+ throw new Error('background request attempt no longer owns the status file');
12
+ }
13
+ if (await sha256File(request.configFile) !== request.configDigest) {
14
+ throw new Error('background request config changed since submission');
15
+ }
16
+ process.env.TMF_DEVICE = request.device;
17
+ process.env.TMF_PYTHON = request.pythonBin;
18
+ // The HF backend uses cwd for its transient spec/output directories. Keep
19
+ // separate background requests from racing on those files.
20
+ process.chdir(path.dirname(statusFile));
21
+ const common = { ...old };
22
+ await writeJson(statusFile, { ...common, state: 'running', pid: process.pid, startedAt: new Date().toISOString() });
23
+ try {
24
+ const { report } = await evaluate({ ...request, reportFile: request.stageReportFile });
25
+ const published = { ...report, backgroundRequest: { requestId: request.requestId, attempt: request.attempt } };
26
+ delete published.reportFile;
27
+ published.reportDigest = sha256Json({ ...published, reportDigest: undefined });
28
+ await writeJson(request.reportFile, published);
29
+ await writeJson(statusFile, {
30
+ ...common, state: 'succeeded', pid: process.pid, finishedAt: new Date().toISOString(),
31
+ reportDigest: published.reportDigest, verdict: published.verdict, gates: published.gates,
32
+ });
33
+ } catch (err) {
34
+ await writeJson(statusFile, {
35
+ ...common, state: 'failed', pid: process.pid, finishedAt: new Date().toISOString(),
36
+ error: { code: err?.code ?? 'action-failed', message: err?.message ?? String(err) },
37
+ });
38
+ process.exitCode = 1;
39
+ }
@@ -0,0 +1,125 @@
1
+ // Background evaluations use a transient user service when available, outside
2
+ // the Gateway cgroup. Every attempt owns its report; old output is never proof
3
+ // that a new attempt finished.
4
+ import { spawn, execFile } from 'node:child_process';
5
+ import { promisify } from 'node:util';
6
+ import { open, mkdir } from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { loadConfig } from '../config.mjs';
10
+ import { ensureDir, exists, readJsonIfExists, writeJson } from '../core/fsx.mjs';
11
+ import { sha256File, sha256Json } from '../core/hash.mjs';
12
+
13
+ const workerFile = fileURLToPath(new URL('./async-evaluate-worker.mjs', import.meta.url));
14
+ const execFileAsync = promisify(execFile);
15
+
16
+ function requireJobId(jobId) {
17
+ if (typeof jobId !== 'string' || !/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,127}$/.test(jobId) || jobId === '..') {
18
+ throw new Error('background evaluation requires a safe, explicit jobId');
19
+ }
20
+ return jobId;
21
+ }
22
+
23
+ async function location({ baseDir, configFile, jobId, requestId }) {
24
+ const { file, config } = await loadConfig({ file: configFile, baseDir });
25
+ const root = path.join(config.runRootAbsolute, requireJobId(jobId), 'plugin-evaluations');
26
+ const dir = path.join(root, requestId);
27
+ return { file, root, dir, statusFile: path.join(dir, 'status.json') };
28
+ }
29
+
30
+ function reportMatches(report, status) {
31
+ if (report?.backgroundRequest?.requestId !== status.requestId || report?.backgroundRequest?.attempt !== status.attempt) return false;
32
+ return report.reportDigest === sha256Json({ ...report, reportDigest: undefined });
33
+ }
34
+
35
+ async function launchWorker(requestFile, statusFile, unit, logFile) {
36
+ if (process.env.TMF_EVAL_LAUNCHER !== 'direct' && process.platform === 'linux') {
37
+ try {
38
+ await execFileAsync('systemd-run', ['--user', '--collect', '--unit=' + unit, process.execPath, workerFile, requestFile, statusFile], { timeout: 10000 });
39
+ return { launcher: 'systemd', unit, restartDurable: true };
40
+ } catch (err) {
41
+ if (process.env.TMF_EVAL_LAUNCHER === 'systemd') throw err;
42
+ }
43
+ }
44
+ const log = await open(logFile, 'a');
45
+ try {
46
+ const child = spawn(process.execPath, [workerFile, requestFile, statusFile], {
47
+ detached: true, stdio: ['ignore', log.fd, log.fd], env: process.env,
48
+ });
49
+ if (!child.pid) throw new Error('background evaluation worker did not start');
50
+ child.unref();
51
+ return { launcher: 'direct', restartDurable: false, pid: child.pid };
52
+ } finally {
53
+ await log.close();
54
+ }
55
+ }
56
+
57
+ export async function startBackgroundEvaluation({ baseDir, configFile, jobId, gates = null, reportFile = null, maxNewTokens = 48, retry = false }) {
58
+ requireJobId(jobId);
59
+ const { file, config } = await loadConfig({ file: configFile, baseDir });
60
+ const output = path.resolve(config.baseDir, reportFile ?? path.join(config.runRootAbsolute, jobId, 'eval-report.json'));
61
+ const device = process.env.TMF_DEVICE ?? 'cpu';
62
+ if (!['cpu', 'cuda'].includes(device)) throw new Error('unsupported TMF_DEVICE=' + device);
63
+ const request = { configFile: file, configDigest: await sha256File(file), jobId, gates, reportFile: output, maxNewTokens, device, pythonBin: process.env.TMF_PYTHON ?? 'python3' };
64
+ const requestId = sha256Json(request).slice(0, 24);
65
+ const loc = await location({ baseDir, configFile: file, jobId, requestId });
66
+ await ensureDir(loc.root);
67
+ let attempt = 1;
68
+ try {
69
+ await mkdir(loc.dir);
70
+ } catch (err) {
71
+ if (err.code !== 'EEXIST') throw err;
72
+ const prior = await backgroundEvaluationStatus({ baseDir, configFile: file, jobId, requestId });
73
+ if (!retry || !['interrupted', 'failed'].includes(prior.state)) return prior;
74
+ attempt = (prior.attempt ?? 1) + 1;
75
+ }
76
+ const attemptDir = path.join(loc.dir, 'attempt-' + attempt);
77
+ try {
78
+ await mkdir(attemptDir);
79
+ } catch (err) {
80
+ if (err.code !== 'EEXIST') throw err;
81
+ return backgroundEvaluationStatus({ baseDir, configFile: file, jobId, requestId });
82
+ }
83
+ const requestFile = path.join(attemptDir, 'request.json');
84
+ await writeJson(requestFile, { ...request, requestId, attempt, stageReportFile: path.join(attemptDir, 'report.json') });
85
+ const status = { requestId, jobId, state: 'queued', attempt, reportFile: output, createdAt: new Date().toISOString(), device };
86
+ await writeJson(loc.statusFile, status);
87
+ try {
88
+ const launch = await launchWorker(requestFile, loc.statusFile, 'tmf-eval-' + requestId + '-' + attempt, path.join(attemptDir, 'worker.log'));
89
+ const now = await readJsonIfExists(loc.statusFile);
90
+ if (now?.state === 'queued' && now.attempt === attempt) await writeJson(loc.statusFile, { ...now, ...launch });
91
+ } catch (err) {
92
+ await writeJson(loc.statusFile, { ...status, state: 'failed', error: { code: 'WORKER_LAUNCH_FAILED', message: err.message }, finishedAt: new Date().toISOString() });
93
+ }
94
+ return backgroundEvaluationStatus({ baseDir, configFile: file, jobId, requestId });
95
+ }
96
+
97
+ export async function backgroundEvaluationStatus({ baseDir, configFile, jobId, requestId }) {
98
+ requireJobId(jobId);
99
+ if (typeof requestId !== 'string' || !/^[a-f0-9]{24}$/.test(requestId)) throw new Error('requestId must be a 24-character hex digest');
100
+ const loc = await location({ baseDir, configFile, jobId, requestId });
101
+ const status = await readJsonIfExists(loc.statusFile);
102
+ if (!status) {
103
+ if (!(await exists(loc.dir))) throw new Error('background evaluation not found: ' + requestId);
104
+ return { requestId, jobId, state: 'initializing', statusFile: loc.statusFile };
105
+ }
106
+ if (status.state === 'running' && status.pid) {
107
+ try {
108
+ process.kill(status.pid, 0);
109
+ } catch (err) {
110
+ if (err.code === 'ESRCH') {
111
+ const report = await readJsonIfExists(status.reportFile);
112
+ if (reportMatches(report, status)) {
113
+ const succeeded = { ...status, state: 'succeeded', finishedAt: report.finishedAt, reportDigest: report.reportDigest, verdict: report.verdict, gates: report.gates };
114
+ delete succeeded.error;
115
+ await writeJson(loc.statusFile, succeeded);
116
+ return { ...succeeded, statusFile: loc.statusFile };
117
+ }
118
+ const interrupted = { ...status, state: 'interrupted', finishedAt: new Date().toISOString(), error: { code: 'WORKER_EXITED', message: 'worker exited without a matching final report; retry the same request explicitly' } };
119
+ await writeJson(loc.statusFile, interrupted);
120
+ return { ...interrupted, statusFile: loc.statusFile };
121
+ }
122
+ }
123
+ }
124
+ return { ...status, statusFile: loc.statusFile };
125
+ }