taskforce-model-foundry 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +133 -2
- package/bin/tmf.mjs +353 -0
- package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
- package/docs/acceptance/r1-r7-reconciliation.md +185 -0
- package/docs/integration.md +227 -0
- package/docs/tutorial.md +336 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
- package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
- package/integrations/hermes-plugin/tests/test_register.py +230 -0
- package/integrations/openclaw-plugin/index.mjs +27 -0
- package/integrations/openclaw-plugin/tools.mjs +70 -0
- package/openclaw.plugin.json +24 -0
- package/package.json +70 -4
- package/scripts/e2e-demo.sh +56 -0
- package/src/api.mjs +341 -0
- package/src/config.mjs +342 -0
- package/src/core/autograd.mjs +451 -0
- package/src/core/fsx.mjs +65 -0
- package/src/core/hash.mjs +47 -0
- package/src/core/rng.mjs +70 -0
- package/src/data/clean.mjs +115 -0
- package/src/data/dedupe.mjs +125 -0
- package/src/data/ingest.mjs +184 -0
- package/src/data/pii.mjs +142 -0
- package/src/data/pipeline.mjs +183 -0
- package/src/data/provenance.mjs +88 -0
- package/src/data/split.mjs +193 -0
- package/src/data/synth.mjs +198 -0
- package/src/eval/evaluator.mjs +124 -0
- package/src/eval/gates.mjs +114 -0
- package/src/eval/metrics.mjs +90 -0
- package/src/export/package.mjs +365 -0
- package/src/index.mjs +26 -0
- package/src/integrations/hermes.mjs +177 -0
- package/src/integrations/openclaw.mjs +154 -0
- package/src/jobs/evaluate.mjs +164 -0
- package/src/jobs/runner.mjs +323 -0
- package/src/jobs/train.mjs +303 -0
- package/src/model/lora.mjs +53 -0
- package/src/model/tokenizer.mjs +73 -0
- package/src/model/transformer.mjs +276 -0
- package/src/train/backends/builtin-js.mjs +367 -0
- package/src/train/backends/hf-peft.mjs +549 -0
- package/src/train/backends/hf_peft_runner.py +326 -0
- package/src/train/backends/index.mjs +92 -0
- package/src/train/dataset.mjs +56 -0
- package/src/train/optimizer.mjs +99 -0
- package/src/version.mjs +5 -0
|
@@ -0,0 +1,154 @@
|
|
|
1
|
+
// OpenClaw adapter.
|
|
2
|
+
//
|
|
3
|
+
// OpenClaw hosts load foundry capability as an in-process tool provider: the
|
|
4
|
+
// host passes an action name plus a JSON params object and expects a
|
|
5
|
+
// JSON-serializable envelope back, never a thrown exception and never a shell
|
|
6
|
+
// out. Everything here therefore goes through src/api.mjs, so the adapter and
|
|
7
|
+
// the `tmf` CLI cannot drift apart.
|
|
8
|
+
//
|
|
9
|
+
// The contract this module promises to an OpenClaw host:
|
|
10
|
+
// * `manifest()` is static, side-effect free, and declares every action with
|
|
11
|
+
// its accepted params and whether invoking it consumes compute.
|
|
12
|
+
// * `invoke(action, params)` always resolves to
|
|
13
|
+
// `{ ok, contractVersion, action, result }` or
|
|
14
|
+
// `{ ok: false, contractVersion, action, error: { code, message } }`.
|
|
15
|
+
// * Unknown actions, unknown params and unauthorized compute are errors with
|
|
16
|
+
// stable codes, not crashes.
|
|
17
|
+
// * No config value is echoed back verbatim; results are the API records.
|
|
18
|
+
|
|
19
|
+
import * as api from '../api.mjs';
|
|
20
|
+
import { VERSION } from '../version.mjs';
|
|
21
|
+
|
|
22
|
+
/** Bumped only on a breaking change to the action set or envelope shape. */
|
|
23
|
+
export const CONTRACT_VERSION = 1;
|
|
24
|
+
export const HOST = 'openclaw';
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Action table. `compute: true` marks actions that spend real CPU/GPU time and
|
|
28
|
+
* write run artifacts, which a host may gate behind its own authority check.
|
|
29
|
+
*/
|
|
30
|
+
const ACTIONS = {
|
|
31
|
+
doctor: {
|
|
32
|
+
summary: 'Environment and configuration self-check; reports every check.',
|
|
33
|
+
params: ['configFile', 'requireConfig'],
|
|
34
|
+
compute: false,
|
|
35
|
+
handler: (ctx, p) => api.doctor({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, requireConfig: p.requireConfig ?? false }),
|
|
36
|
+
},
|
|
37
|
+
status: {
|
|
38
|
+
summary: 'Durable job state plus a tail of its audit log.',
|
|
39
|
+
params: ['jobId', 'configFile', 'auditTail'],
|
|
40
|
+
compute: false,
|
|
41
|
+
required: ['jobId'],
|
|
42
|
+
handler: (ctx, p) => api.status({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId, auditTail: p.auditTail ?? 10 }),
|
|
43
|
+
},
|
|
44
|
+
synthesize: {
|
|
45
|
+
summary: 'Write a synthetic training corpus (no private data involved).',
|
|
46
|
+
params: ['outDir', 'seed', 'count', 'profile'],
|
|
47
|
+
compute: true,
|
|
48
|
+
handler: (ctx, p) => api.synthesize({ baseDir: ctx.baseDir, ...p }),
|
|
49
|
+
},
|
|
50
|
+
train: {
|
|
51
|
+
summary: 'Run a post-training job that updates real weights or an adapter.',
|
|
52
|
+
params: ['configFile', 'jobId', 'resume', 'resumeCancelled', 'auditEveryStep'],
|
|
53
|
+
compute: true,
|
|
54
|
+
handler: (ctx, p) => api.train({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, resume: p.resume ?? true, resumeCancelled: p.resumeCancelled ?? false, auditEveryStep: p.auditEveryStep ?? 10 }),
|
|
55
|
+
},
|
|
56
|
+
evaluate: {
|
|
57
|
+
summary: 'Score base vs trained model on the independent holdout and apply gates.',
|
|
58
|
+
params: ['configFile', 'jobId', 'gates', 'reportFile', 'maxNewTokens'],
|
|
59
|
+
compute: true,
|
|
60
|
+
handler: (ctx, p) => api.evaluate({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, gates: p.gates ?? null, reportFile: p.reportFile ?? null, maxNewTokens: p.maxNewTokens ?? 48 }),
|
|
61
|
+
},
|
|
62
|
+
export: {
|
|
63
|
+
summary: 'Package weights/adapter with lineage, model card and checksums.',
|
|
64
|
+
params: ['configFile', 'jobId', 'evalReport', 'outDir', 'version', 'evaluateIfMissing'],
|
|
65
|
+
compute: true,
|
|
66
|
+
handler: (ctx, p) => api.exportModel({ baseDir: ctx.baseDir, configFile: p.configFile ?? ctx.configFile ?? null, jobId: p.jobId ?? null, evalReport: p.evalReport ?? null, outDir: p.outDir ?? null, version: p.version ?? null, evaluateIfMissing: p.evaluateIfMissing ?? true }),
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
export const ACTION_NAMES = Object.freeze(Object.keys(ACTIONS));
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* The action table itself, shared with the other host adapters (see
|
|
74
|
+
* src/integrations/hermes.mjs) so a second host cannot drift from this one:
|
|
75
|
+
* one action set, one set of handlers, one place to add an action.
|
|
76
|
+
*/
|
|
77
|
+
export const ACTION_SPECS = Object.freeze(ACTIONS);
|
|
78
|
+
|
|
79
|
+
/** Static, side-effect-free description of what this adapter offers a host. */
|
|
80
|
+
export function manifest() {
|
|
81
|
+
return {
|
|
82
|
+
host: HOST,
|
|
83
|
+
product: api.PRODUCT,
|
|
84
|
+
toolkitVersion: VERSION,
|
|
85
|
+
contractVersion: CONTRACT_VERSION,
|
|
86
|
+
transport: 'in-process',
|
|
87
|
+
actions: ACTION_NAMES.map((name) => ({
|
|
88
|
+
name,
|
|
89
|
+
summary: ACTIONS[name].summary,
|
|
90
|
+
params: [...ACTIONS[name].params],
|
|
91
|
+
required: [...(ACTIONS[name].required ?? [])],
|
|
92
|
+
compute: ACTIONS[name].compute,
|
|
93
|
+
})),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
function fail(action, code, message) {
|
|
98
|
+
return { ok: false, contractVersion: CONTRACT_VERSION, action, error: { code, message } };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Build an adapter bound to one workspace.
|
|
103
|
+
*
|
|
104
|
+
* `allowCompute: false` lets a host mount the adapter for inspection only —
|
|
105
|
+
* doctor and status still answer, while anything that would burn compute or
|
|
106
|
+
* write artifacts is refused with `compute-not-authorized` instead of running.
|
|
107
|
+
*/
|
|
108
|
+
export function createOpenClawAdapter({ baseDir = process.cwd(), configFile = null, allowCompute = true } = {}) {
|
|
109
|
+
const ctx = { baseDir, configFile };
|
|
110
|
+
|
|
111
|
+
async function invoke(action, params = {}) {
|
|
112
|
+
if (typeof action !== 'string' || !action) {
|
|
113
|
+
return fail(String(action), 'invalid-action', 'action must be a non-empty string');
|
|
114
|
+
}
|
|
115
|
+
const spec = ACTIONS[action];
|
|
116
|
+
if (!spec) {
|
|
117
|
+
return fail(action, 'unknown-action', `unknown action "${action}"; known actions: ${ACTION_NAMES.join(', ')}`);
|
|
118
|
+
}
|
|
119
|
+
if (params === null || typeof params !== 'object' || Array.isArray(params)) {
|
|
120
|
+
return fail(action, 'invalid-params', 'params must be a plain object');
|
|
121
|
+
}
|
|
122
|
+
const unknown = Object.keys(params).filter((k) => !spec.params.includes(k));
|
|
123
|
+
if (unknown.length) {
|
|
124
|
+
return fail(action, 'unknown-params', `unknown params for "${action}": ${unknown.join(', ')}`);
|
|
125
|
+
}
|
|
126
|
+
const missing = (spec.required ?? []).filter((k) => params[k] === undefined || params[k] === null);
|
|
127
|
+
if (missing.length) {
|
|
128
|
+
return fail(action, 'missing-params', `action "${action}" requires: ${missing.join(', ')}`);
|
|
129
|
+
}
|
|
130
|
+
if (spec.compute && !allowCompute) {
|
|
131
|
+
return fail(action, 'compute-not-authorized', `action "${action}" consumes compute and this adapter was mounted read-only`);
|
|
132
|
+
}
|
|
133
|
+
try {
|
|
134
|
+
const result = await spec.handler(ctx, params);
|
|
135
|
+
return { ok: true, contractVersion: CONTRACT_VERSION, action, result };
|
|
136
|
+
} catch (err) {
|
|
137
|
+
const code = err?.code && typeof err.code === 'string' ? err.code : err?.name === 'ConfigError' ? 'config-error' : 'action-failed';
|
|
138
|
+
return fail(action, code, err?.message ?? String(err));
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
return { host: HOST, baseDir, allowCompute, manifest, actions: ACTION_NAMES, invoke };
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** Registration entry point for an OpenClaw plugin host. */
|
|
146
|
+
export function register(host, options = {}) {
|
|
147
|
+
const adapter = createOpenClawAdapter(options);
|
|
148
|
+
if (host && typeof host.registerToolProvider === 'function') {
|
|
149
|
+
host.registerToolProvider({ name: api.PRODUCT, manifest: manifest(), invoke: adapter.invoke });
|
|
150
|
+
}
|
|
151
|
+
return adapter;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
export default { CONTRACT_VERSION, HOST, manifest, createOpenClawAdapter, register, ACTION_NAMES };
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// The evaluation job.
|
|
2
|
+
//
|
|
3
|
+
// A re-runnable unit of work that turns a checkpoint pair plus held-out data
|
|
4
|
+
// into a gate verdict and a lineage-bearing report. It is deliberately the
|
|
5
|
+
// only place allowed to decide whether a run may be described as an
|
|
6
|
+
// improvement: `verdict.improvementClaimAllowed` is false unless the gates
|
|
7
|
+
// actually passed, and `assertDeliverable` is what export paths call so a
|
|
8
|
+
// failed gate is terminal rather than advisory.
|
|
9
|
+
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import { evaluateGates, DEFAULT_GATES } from '../eval/gates.mjs';
|
|
12
|
+
import {
|
|
13
|
+
EVAL_REPORT_FORMAT, assertHoldoutIndependence, evaluateSplitSet, assembleMetrics,
|
|
14
|
+
} from '../eval/evaluator.mjs';
|
|
15
|
+
import { sha256File, sha256Json } from '../core/hash.mjs';
|
|
16
|
+
import { writeJson, exists } from '../core/fsx.mjs';
|
|
17
|
+
|
|
18
|
+
// A report handed in from outside (`tmf export --report`) is only usable as a
|
|
19
|
+
// gate record if it still hashes to its own `reportDigest`: otherwise the
|
|
20
|
+
// bundle would claim lineage for numbers nobody evaluated.
|
|
21
|
+
export function assertReportIntegrity(report, { jobId = null } = {}) {
|
|
22
|
+
if (!report || typeof report !== 'object') throw new Error('eval report must be an object');
|
|
23
|
+
if (report.format !== EVAL_REPORT_FORMAT) {
|
|
24
|
+
throw new Error(`eval report format mismatch: expected ${EVAL_REPORT_FORMAT}, got ${report.format ?? 'none'}`);
|
|
25
|
+
}
|
|
26
|
+
if (!report.reportDigest) throw new Error('eval report is missing reportDigest');
|
|
27
|
+
// Mirror how the digest was produced: `reportDigest` stays as an undefined
|
|
28
|
+
// key (which canonicalizes to null), while `reportFile` — attached only
|
|
29
|
+
// in-memory after the write — must be absent, not undefined.
|
|
30
|
+
const canonical = { ...report, reportDigest: undefined };
|
|
31
|
+
delete canonical.reportFile;
|
|
32
|
+
const recomputed = sha256Json(canonical);
|
|
33
|
+
if (recomputed !== report.reportDigest) {
|
|
34
|
+
throw new Error(`eval report digest mismatch: file claims ${report.reportDigest}, contents hash to ${recomputed}`);
|
|
35
|
+
}
|
|
36
|
+
const reportJob = report.lineage?.jobId ?? null;
|
|
37
|
+
if (jobId && reportJob && reportJob !== jobId) {
|
|
38
|
+
throw new Error(`eval report belongs to job ${reportJob}, not ${jobId}`);
|
|
39
|
+
}
|
|
40
|
+
return report;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
async function checkpointRef(file) {
|
|
44
|
+
if (!file) return null;
|
|
45
|
+
if (!(await exists(file))) throw new Error(`checkpoint not found: ${file}`);
|
|
46
|
+
return { file, sha256: await sha256File(file) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export async function runEvaluationJob({
|
|
50
|
+
backend,
|
|
51
|
+
baseCheckpoint,
|
|
52
|
+
adapterCheckpoint = null,
|
|
53
|
+
tunedCheckpoint = null,
|
|
54
|
+
encoded,
|
|
55
|
+
records = {},
|
|
56
|
+
gates = DEFAULT_GATES,
|
|
57
|
+
lineage = {},
|
|
58
|
+
reportFile = null,
|
|
59
|
+
maxNewTokens = 48,
|
|
60
|
+
jobId = null,
|
|
61
|
+
clock = () => new Date().toISOString(),
|
|
62
|
+
} = {}) {
|
|
63
|
+
if (!backend) throw new Error('runEvaluationJob needs a backend');
|
|
64
|
+
if (!baseCheckpoint) throw new Error('runEvaluationJob needs a base checkpoint');
|
|
65
|
+
const startedAt = clock();
|
|
66
|
+
|
|
67
|
+
const independence = assertHoldoutIndependence({
|
|
68
|
+
holdout: records.holdout ?? [],
|
|
69
|
+
train: records.train ?? [],
|
|
70
|
+
validation: records.validation ?? [],
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
const baseRef = await checkpointRef(baseCheckpoint);
|
|
74
|
+
const adapterRef = await checkpointRef(adapterCheckpoint);
|
|
75
|
+
const tunedRef = await checkpointRef(tunedCheckpoint);
|
|
76
|
+
|
|
77
|
+
// Baseline is the base checkpoint with no adapter attached. For a LoRA run
|
|
78
|
+
// the tuned side is that same base with the adapter layered on; for a
|
|
79
|
+
// full-parameter run (pretrain / full-finetune) the trainer writes a whole
|
|
80
|
+
// tuned checkpoint instead, and that file is the tuned side. Either way both
|
|
81
|
+
// sides are loaded from disk, which is what makes the comparison independent
|
|
82
|
+
// of trainer state -- and without the full-checkpoint path those modes could
|
|
83
|
+
// never produce gates, so export stayed permanently blocked for them.
|
|
84
|
+
const baselineHandle = await backend.loadModel({ file: baseCheckpoint });
|
|
85
|
+
const baselineFingerprint = backend.fingerprint(baselineHandle);
|
|
86
|
+
const baseline = await evaluateSplitSet(backend, baselineHandle, { encoded, records, maxNewTokens });
|
|
87
|
+
|
|
88
|
+
let tuned = null;
|
|
89
|
+
let tunedFingerprint = null;
|
|
90
|
+
if (adapterCheckpoint || tunedCheckpoint) {
|
|
91
|
+
const tunedHandle = adapterCheckpoint
|
|
92
|
+
? await backend.loadModel({ file: baseCheckpoint, attachAdapter: adapterCheckpoint })
|
|
93
|
+
: await backend.loadModel({ file: tunedCheckpoint });
|
|
94
|
+
tunedFingerprint = backend.fingerprint(tunedHandle);
|
|
95
|
+
tuned = await evaluateSplitSet(backend, tunedHandle, { encoded, records, maxNewTokens });
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
const metrics = assembleMetrics({ baseline, tuned });
|
|
99
|
+
const verdictGates = tuned ? evaluateGates(metrics, gates) : null;
|
|
100
|
+
const status = !tuned ? 'baseline_only' : (verdictGates.passed ? 'passed' : 'failed');
|
|
101
|
+
|
|
102
|
+
const report = {
|
|
103
|
+
format: EVAL_REPORT_FORMAT,
|
|
104
|
+
jobId: jobId ?? `eval-${startedAt}`,
|
|
105
|
+
startedAt,
|
|
106
|
+
finishedAt: clock(),
|
|
107
|
+
backend: { id: backend.id, label: backend.label ?? null },
|
|
108
|
+
inputs: {
|
|
109
|
+
baseCheckpoint: baseRef,
|
|
110
|
+
adapterCheckpoint: adapterRef,
|
|
111
|
+
tunedCheckpoint: tunedRef,
|
|
112
|
+
splits: {
|
|
113
|
+
holdout: encoded.holdout?.length ?? 0,
|
|
114
|
+
validation: encoded.validation?.length ?? 0,
|
|
115
|
+
trainWithheld: records.train?.length ?? 0,
|
|
116
|
+
},
|
|
117
|
+
},
|
|
118
|
+
independence,
|
|
119
|
+
metrics,
|
|
120
|
+
gates: verdictGates ?? { passed: false, results: [], failed: [], summary: 'no tuned model to gate' },
|
|
121
|
+
verdict: {
|
|
122
|
+
status,
|
|
123
|
+
improvementClaimAllowed: status === 'passed',
|
|
124
|
+
deliveryEligible: status === 'passed',
|
|
125
|
+
summary: status === 'passed'
|
|
126
|
+
? `improvement confirmed on an independent holdout (${verdictGates.summary})`
|
|
127
|
+
: status === 'failed'
|
|
128
|
+
? `gates failed, no improvement may be claimed (${verdictGates.summary}): ${verdictGates.failed.map((f) => f.reason).join('; ')}`
|
|
129
|
+
: 'baseline-only evaluation: no tuned checkpoint was supplied, so no improvement may be claimed',
|
|
130
|
+
},
|
|
131
|
+
lineage: {
|
|
132
|
+
...lineage,
|
|
133
|
+
// The builtin fingerprint digests the *base* weights, so for an adapter
|
|
134
|
+
// run both handles share it -- that equality is the proof the adapter is
|
|
135
|
+
// bound to this base checkpoint. Adapter bytes are pinned by
|
|
136
|
+
// inputs.adapterCheckpoint.sha256.
|
|
137
|
+
baseFingerprint: baselineFingerprint,
|
|
138
|
+
tunedFingerprint,
|
|
139
|
+
// Only an adapter run can be "bound to base". A full-parameter tuned
|
|
140
|
+
// checkpoint has no adapter, so reporting false there would read as a
|
|
141
|
+
// broken binding instead of "not applicable".
|
|
142
|
+
adapterBoundToBase: adapterCheckpoint ? tunedFingerprint === baselineFingerprint : null,
|
|
143
|
+
gateDefinitions: gates.map((g) => ({ id: g.id, metric: g.metric, comparator: g.comparator, threshold: g.threshold })),
|
|
144
|
+
gateDefinitionsDigest: sha256Json(gates),
|
|
145
|
+
},
|
|
146
|
+
};
|
|
147
|
+
report.reportDigest = sha256Json({ ...report, reportDigest: undefined });
|
|
148
|
+
|
|
149
|
+
if (reportFile) {
|
|
150
|
+
await writeJson(reportFile, report);
|
|
151
|
+
report.reportFile = path.resolve(reportFile);
|
|
152
|
+
}
|
|
153
|
+
return report;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
// Delivery/export gate. Callers that want the non-throwing form read
|
|
157
|
+
// `report.verdict.deliveryEligible` instead.
|
|
158
|
+
export function assertDeliverable(report) {
|
|
159
|
+
if (report?.verdict?.deliveryEligible) return report;
|
|
160
|
+
const err = new Error(`evaluation report is not deliverable: ${report?.verdict?.summary ?? 'missing verdict'}`);
|
|
161
|
+
err.code = 'EVAL_NOT_DELIVERABLE';
|
|
162
|
+
err.report = report;
|
|
163
|
+
throw err;
|
|
164
|
+
}
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// Auditable job orchestration.
|
|
2
|
+
//
|
|
3
|
+
// Every long-running foundry job (data prep, training, evaluation, export) runs
|
|
4
|
+
// through this runner so the operator gets the same guarantees regardless of
|
|
5
|
+
// which job it is: a durable state machine, an append-only audit log that is
|
|
6
|
+
// safe to hand to a reviewer, resume after a crash, cooperative cancellation,
|
|
7
|
+
// hard budget caps, and replay that does not redo completed side effects.
|
|
8
|
+
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { appendJsonl, ensureDir, readJsonIfExists, readJsonl, writeJson } from '../core/fsx.mjs';
|
|
11
|
+
import { sha256Json } from '../core/hash.mjs';
|
|
12
|
+
import { redactPii } from '../data/pii.mjs';
|
|
13
|
+
|
|
14
|
+
export const JOB_STATES = ['pending', 'running', 'succeeded', 'failed', 'cancelled', 'budget_exceeded'];
|
|
15
|
+
|
|
16
|
+
const TERMINAL_STATES = new Set(['succeeded', 'failed', 'cancelled', 'budget_exceeded']);
|
|
17
|
+
|
|
18
|
+
// Only these transitions are legal. An illegal transition is a bug in a job
|
|
19
|
+
// implementation, so it throws rather than being recorded as job failure.
|
|
20
|
+
const TRANSITIONS = {
|
|
21
|
+
pending: ['running', 'cancelled'],
|
|
22
|
+
running: ['running', 'succeeded', 'failed', 'cancelled', 'budget_exceeded'],
|
|
23
|
+
succeeded: [],
|
|
24
|
+
failed: [],
|
|
25
|
+
// Operator cancellation is a pause, not a verdict: the completed steps are
|
|
26
|
+
// still valid, so an explicit `resumeCancelled` run continues the same job.
|
|
27
|
+
cancelled: ['running'],
|
|
28
|
+
budget_exceeded: [],
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
// Matched against the normalized key, exactly: a budget field named `tokens`
|
|
32
|
+
// or `maxTokens` must stay readable while an `accessToken` must not.
|
|
33
|
+
const SECRET_KEYS = new Set([
|
|
34
|
+
'token', 'accesstoken', 'refreshtoken', 'idtoken', 'authtoken', 'sessiontoken',
|
|
35
|
+
'secret', 'clientsecret', 'password', 'passwd', 'pwd', 'passphrase',
|
|
36
|
+
'apikey', 'apisecret', 'credential', 'credentials', 'authorization', 'auth',
|
|
37
|
+
'cookie', 'bearer', 'privatekey', 'sessionkey', 'signingkey',
|
|
38
|
+
]);
|
|
39
|
+
const REDACTED = '[REDACTED]';
|
|
40
|
+
|
|
41
|
+
export class JobCancelledError extends Error {
|
|
42
|
+
constructor(message = 'job cancelled') {
|
|
43
|
+
super(message);
|
|
44
|
+
this.name = 'JobCancelledError';
|
|
45
|
+
this.code = 'JOB_CANCELLED';
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class BudgetExceededError extends Error {
|
|
50
|
+
constructor(message, details = {}) {
|
|
51
|
+
super(message);
|
|
52
|
+
this.name = 'BudgetExceededError';
|
|
53
|
+
this.code = 'JOB_BUDGET_EXCEEDED';
|
|
54
|
+
this.details = details;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function assertTransition(from, to) {
|
|
59
|
+
if (!JOB_STATES.includes(to)) throw new Error(`unknown job state: ${to}`);
|
|
60
|
+
const allowed = TRANSITIONS[from] ?? [];
|
|
61
|
+
if (!allowed.includes(to)) {
|
|
62
|
+
throw new Error(`illegal job state transition: ${from} -> ${to}`);
|
|
63
|
+
}
|
|
64
|
+
return to;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function isTerminal(state) {
|
|
68
|
+
return TERMINAL_STATES.has(state);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
// Redaction is applied to everything that reaches the audit log. Keys that name
|
|
72
|
+
// a credential are dropped wholesale (the value shape itself can leak); free
|
|
73
|
+
// text goes through the same PII rules the data pipeline uses.
|
|
74
|
+
export function isSecretKey(key) {
|
|
75
|
+
return SECRET_KEYS.has(String(key).replace(/[^a-z0-9]/gi, '').toLowerCase());
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export function redactForAudit(value, depth = 0) {
|
|
79
|
+
if (depth > 8) return '[TRUNCATED]';
|
|
80
|
+
if (value === null || value === undefined) return value ?? null;
|
|
81
|
+
if (typeof value === 'string') return redactPii(value).text;
|
|
82
|
+
if (typeof value === 'number' || typeof value === 'boolean') return value;
|
|
83
|
+
if (Array.isArray(value)) return value.map((item) => redactForAudit(item, depth + 1));
|
|
84
|
+
if (typeof value === 'object') {
|
|
85
|
+
const out = {};
|
|
86
|
+
for (const [key, item] of Object.entries(value)) {
|
|
87
|
+
out[key] = isSecretKey(key) ? REDACTED : redactForAudit(item, depth + 1);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
return String(value);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export class JobBudget {
|
|
95
|
+
constructor({ maxSteps = null, maxWallClockMs = null, maxTokens = null, maxCostUsd = null } = {}) {
|
|
96
|
+
this.limits = { maxSteps, maxWallClockMs, maxTokens, maxCostUsd };
|
|
97
|
+
this.usage = { steps: 0, wallClockMs: 0, tokens: 0, costUsd: 0 };
|
|
98
|
+
this.startedAt = null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
start(now) {
|
|
102
|
+
this.startedAt = now;
|
|
103
|
+
return this;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Charged before a step runs so an over-budget job stops instead of spending.
|
|
107
|
+
charge({ steps = 0, tokens = 0, costUsd = 0 } = {}, now = Date.now()) {
|
|
108
|
+
const next = {
|
|
109
|
+
steps: this.usage.steps + steps,
|
|
110
|
+
tokens: this.usage.tokens + tokens,
|
|
111
|
+
costUsd: this.usage.costUsd + costUsd,
|
|
112
|
+
wallClockMs: this.startedAt === null ? 0 : now - this.startedAt,
|
|
113
|
+
};
|
|
114
|
+
const checks = [
|
|
115
|
+
['maxSteps', next.steps, 'steps'],
|
|
116
|
+
['maxTokens', next.tokens, 'tokens'],
|
|
117
|
+
['maxCostUsd', next.costUsd, 'costUsd'],
|
|
118
|
+
['maxWallClockMs', next.wallClockMs, 'wallClockMs'],
|
|
119
|
+
];
|
|
120
|
+
for (const [limitKey, value, usageKey] of checks) {
|
|
121
|
+
const limit = this.limits[limitKey];
|
|
122
|
+
if (limit !== null && limit !== undefined && value > limit) {
|
|
123
|
+
throw new BudgetExceededError(`budget exceeded: ${usageKey} ${value} > ${limit}`, {
|
|
124
|
+
limit: limitKey,
|
|
125
|
+
limitValue: limit,
|
|
126
|
+
attempted: value,
|
|
127
|
+
usage: { ...this.usage },
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
this.usage = next;
|
|
132
|
+
return this.usage;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
snapshot(now = Date.now()) {
|
|
136
|
+
return {
|
|
137
|
+
limits: { ...this.limits },
|
|
138
|
+
usage: { ...this.usage, wallClockMs: this.startedAt === null ? this.usage.wallClockMs : now - this.startedAt },
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function jobPaths(root, jobId) {
|
|
144
|
+
const dir = path.join(root, jobId);
|
|
145
|
+
return {
|
|
146
|
+
dir,
|
|
147
|
+
state: path.join(dir, 'state.json'),
|
|
148
|
+
audit: path.join(dir, 'audit.jsonl'),
|
|
149
|
+
result: path.join(dir, 'result.json'),
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
export async function readJobState(root, jobId) {
|
|
154
|
+
return readJsonIfExists(jobPaths(root, jobId).state, null);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
export async function readAuditLog(root, jobId) {
|
|
158
|
+
const rows = await readJsonl(jobPaths(root, jobId).audit).catch(() => []);
|
|
159
|
+
return rows;
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
// A job is a declarative list of named steps. Each step's recorded output is the
|
|
163
|
+
// resume unit: on replay a step whose record already exists is skipped and its
|
|
164
|
+
// stored output is reused, so completed side effects are never repeated.
|
|
165
|
+
export async function runJob({
|
|
166
|
+
jobId,
|
|
167
|
+
kind,
|
|
168
|
+
root,
|
|
169
|
+
steps,
|
|
170
|
+
input = {},
|
|
171
|
+
budget = {},
|
|
172
|
+
signal = null,
|
|
173
|
+
now = () => Date.now(),
|
|
174
|
+
resume = true,
|
|
175
|
+
resumeCancelled = false,
|
|
176
|
+
} = {}) {
|
|
177
|
+
if (!jobId) throw new Error('runJob requires jobId');
|
|
178
|
+
if (!kind) throw new Error('runJob requires kind');
|
|
179
|
+
if (!root) throw new Error('runJob requires root');
|
|
180
|
+
if (!Array.isArray(steps) || steps.length === 0) throw new Error('runJob requires at least one step');
|
|
181
|
+
|
|
182
|
+
const paths = jobPaths(root, jobId);
|
|
183
|
+
await ensureDir(paths.dir);
|
|
184
|
+
|
|
185
|
+
const inputDigest = sha256Json(input);
|
|
186
|
+
const planDigest = sha256Json(steps.map((step) => ({ name: step.name, cost: step.cost ?? null })));
|
|
187
|
+
|
|
188
|
+
const prior = resume ? await readJsonIfExists(paths.state, null) : null;
|
|
189
|
+
if (prior) {
|
|
190
|
+
if (prior.inputDigest !== inputDigest || prior.planDigest !== planDigest) {
|
|
191
|
+
throw new Error(
|
|
192
|
+
`job ${jobId} already exists with a different input/plan digest; use a new jobId instead of mutating history`,
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
// Idempotency: a finished job is returned as-is, not re-executed. The one
|
|
196
|
+
// exception is a cancelled job the caller explicitly asks to continue,
|
|
197
|
+
// which picks up at the first step that never completed.
|
|
198
|
+
const continuable = prior.state === 'cancelled' && resumeCancelled;
|
|
199
|
+
if (isTerminal(prior.state) && !continuable) {
|
|
200
|
+
const result = await readJsonIfExists(paths.result, null);
|
|
201
|
+
return { ...prior, replayed: true, result: result?.result ?? null };
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const jobBudget = new JobBudget({ ...(prior?.budget?.limits ?? {}), ...budget });
|
|
206
|
+
jobBudget.usage = { ...jobBudget.usage, ...(prior?.budget?.usage ?? {}) };
|
|
207
|
+
const startedAt = prior?.startedAt ?? new Date(now()).toISOString();
|
|
208
|
+
jobBudget.start(now());
|
|
209
|
+
|
|
210
|
+
let state = {
|
|
211
|
+
version: 1,
|
|
212
|
+
jobId,
|
|
213
|
+
kind,
|
|
214
|
+
state: prior?.state ?? 'pending',
|
|
215
|
+
attempt: (prior?.attempt ?? 0) + 1,
|
|
216
|
+
inputDigest,
|
|
217
|
+
planDigest,
|
|
218
|
+
startedAt,
|
|
219
|
+
updatedAt: startedAt,
|
|
220
|
+
completedSteps: prior?.completedSteps ?? [],
|
|
221
|
+
budget: jobBudget.snapshot(now()),
|
|
222
|
+
error: null,
|
|
223
|
+
};
|
|
224
|
+
|
|
225
|
+
const audit = async (event, payload = {}) => {
|
|
226
|
+
await appendJsonl(paths.audit, {
|
|
227
|
+
ts: new Date(now()).toISOString(),
|
|
228
|
+
jobId,
|
|
229
|
+
kind,
|
|
230
|
+
attempt: state.attempt,
|
|
231
|
+
event,
|
|
232
|
+
...redactForAudit(payload),
|
|
233
|
+
});
|
|
234
|
+
};
|
|
235
|
+
|
|
236
|
+
const persist = async (nextState, extra = {}) => {
|
|
237
|
+
if (nextState && nextState !== state.state) assertTransition(state.state, nextState);
|
|
238
|
+
state = {
|
|
239
|
+
...state,
|
|
240
|
+
...extra,
|
|
241
|
+
state: nextState ?? state.state,
|
|
242
|
+
budget: jobBudget.snapshot(now()),
|
|
243
|
+
updatedAt: new Date(now()).toISOString(),
|
|
244
|
+
};
|
|
245
|
+
await writeJson(paths.state, state);
|
|
246
|
+
return state;
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
const checkCancel = async () => {
|
|
250
|
+
if (signal?.aborted) {
|
|
251
|
+
await audit('job.cancelled', { reason: signal.reason ? String(signal.reason) : 'signal aborted' });
|
|
252
|
+
await persist('cancelled', { error: { code: 'JOB_CANCELLED', message: 'job cancelled' } });
|
|
253
|
+
throw new JobCancelledError();
|
|
254
|
+
}
|
|
255
|
+
};
|
|
256
|
+
|
|
257
|
+
await audit(prior ? 'job.resumed' : 'job.started', {
|
|
258
|
+
inputDigest,
|
|
259
|
+
planDigest,
|
|
260
|
+
completedSteps: state.completedSteps.map((s) => s.name),
|
|
261
|
+
budgetLimits: jobBudget.limits,
|
|
262
|
+
});
|
|
263
|
+
await checkCancel();
|
|
264
|
+
await persist('running');
|
|
265
|
+
|
|
266
|
+
const outputs = {};
|
|
267
|
+
for (const done of state.completedSteps) outputs[done.name] = done.output ?? null;
|
|
268
|
+
|
|
269
|
+
for (const step of steps) {
|
|
270
|
+
if (!step?.name || typeof step.run !== 'function') {
|
|
271
|
+
throw new Error('each step requires { name, run }');
|
|
272
|
+
}
|
|
273
|
+
const already = state.completedSteps.find((s) => s.name === step.name);
|
|
274
|
+
if (already) {
|
|
275
|
+
await audit('step.skipped', { step: step.name, reason: 'already completed in a prior attempt' });
|
|
276
|
+
continue;
|
|
277
|
+
}
|
|
278
|
+
await checkCancel();
|
|
279
|
+
try {
|
|
280
|
+
jobBudget.charge({ steps: 1, ...(step.cost ?? {}) }, now());
|
|
281
|
+
} catch (error) {
|
|
282
|
+
if (error instanceof BudgetExceededError) {
|
|
283
|
+
await audit('job.budget_exceeded', { step: step.name, ...error.details });
|
|
284
|
+
await persist('budget_exceeded', { error: { code: error.code, message: error.message, details: error.details } });
|
|
285
|
+
throw error;
|
|
286
|
+
}
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
await audit('step.started', { step: step.name });
|
|
290
|
+
let output;
|
|
291
|
+
try {
|
|
292
|
+
output = await step.run({ input, outputs, signal, audit, budget: jobBudget });
|
|
293
|
+
} catch (error) {
|
|
294
|
+
if (error instanceof JobCancelledError || signal?.aborted) {
|
|
295
|
+
await audit('job.cancelled', { step: step.name, reason: error.message });
|
|
296
|
+
await persist('cancelled', { error: { code: 'JOB_CANCELLED', message: error.message } });
|
|
297
|
+
throw error instanceof JobCancelledError ? error : new JobCancelledError(error.message);
|
|
298
|
+
}
|
|
299
|
+
if (error instanceof BudgetExceededError) {
|
|
300
|
+
await audit('job.budget_exceeded', { step: step.name, ...error.details });
|
|
301
|
+
await persist('budget_exceeded', { error: { code: error.code, message: error.message, details: error.details } });
|
|
302
|
+
throw error;
|
|
303
|
+
}
|
|
304
|
+
await audit('step.failed', { step: step.name, error: error.message });
|
|
305
|
+
await persist('failed', { error: { code: error.code ?? 'STEP_FAILED', message: error.message, step: step.name } });
|
|
306
|
+
throw error;
|
|
307
|
+
}
|
|
308
|
+
outputs[step.name] = output ?? null;
|
|
309
|
+
state.completedSteps = [
|
|
310
|
+
...state.completedSteps,
|
|
311
|
+
{ name: step.name, completedAt: new Date(now()).toISOString(), output: output ?? null },
|
|
312
|
+
];
|
|
313
|
+
await audit('step.succeeded', { step: step.name, outputDigest: sha256Json(output ?? null) });
|
|
314
|
+
await persist(null, { completedSteps: state.completedSteps });
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
await checkCancel();
|
|
318
|
+
const result = outputs[steps[steps.length - 1].name] ?? null;
|
|
319
|
+
await writeJson(paths.result, { jobId, kind, result, resultDigest: sha256Json(result) });
|
|
320
|
+
await audit('job.succeeded', { resultDigest: sha256Json(result) });
|
|
321
|
+
await persist('succeeded');
|
|
322
|
+
return { ...state, replayed: false, result };
|
|
323
|
+
}
|