taskforce-model-foundry 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +133 -2
  3. package/bin/tmf.mjs +353 -0
  4. package/docs/acceptance/evidence/cp62-eval-report.json +279 -0
  5. package/docs/acceptance/r1-r7-reconciliation.md +185 -0
  6. package/docs/integration.md +227 -0
  7. package/docs/tutorial.md +336 -0
  8. package/integrations/hermes-plugin/taskforce_model_foundry/__init__.py +193 -0
  9. package/integrations/hermes-plugin/taskforce_model_foundry/bridge.mjs +46 -0
  10. package/integrations/hermes-plugin/taskforce_model_foundry/plugin.yaml +7 -0
  11. package/integrations/hermes-plugin/tests/test_register.py +230 -0
  12. package/integrations/openclaw-plugin/index.mjs +27 -0
  13. package/integrations/openclaw-plugin/tools.mjs +70 -0
  14. package/openclaw.plugin.json +24 -0
  15. package/package.json +70 -4
  16. package/scripts/e2e-demo.sh +56 -0
  17. package/src/api.mjs +341 -0
  18. package/src/config.mjs +342 -0
  19. package/src/core/autograd.mjs +451 -0
  20. package/src/core/fsx.mjs +65 -0
  21. package/src/core/hash.mjs +47 -0
  22. package/src/core/rng.mjs +70 -0
  23. package/src/data/clean.mjs +115 -0
  24. package/src/data/dedupe.mjs +125 -0
  25. package/src/data/ingest.mjs +184 -0
  26. package/src/data/pii.mjs +142 -0
  27. package/src/data/pipeline.mjs +183 -0
  28. package/src/data/provenance.mjs +88 -0
  29. package/src/data/split.mjs +193 -0
  30. package/src/data/synth.mjs +198 -0
  31. package/src/eval/evaluator.mjs +124 -0
  32. package/src/eval/gates.mjs +114 -0
  33. package/src/eval/metrics.mjs +90 -0
  34. package/src/export/package.mjs +365 -0
  35. package/src/index.mjs +26 -0
  36. package/src/integrations/hermes.mjs +177 -0
  37. package/src/integrations/openclaw.mjs +154 -0
  38. package/src/jobs/evaluate.mjs +164 -0
  39. package/src/jobs/runner.mjs +323 -0
  40. package/src/jobs/train.mjs +303 -0
  41. package/src/model/lora.mjs +53 -0
  42. package/src/model/tokenizer.mjs +73 -0
  43. package/src/model/transformer.mjs +276 -0
  44. package/src/train/backends/builtin-js.mjs +367 -0
  45. package/src/train/backends/hf-peft.mjs +549 -0
  46. package/src/train/backends/hf_peft_runner.py +326 -0
  47. package/src/train/backends/index.mjs +92 -0
  48. package/src/train/dataset.mjs +56 -0
  49. package/src/train/optimizer.mjs +99 -0
  50. package/src/version.mjs +5 -0
@@ -0,0 +1,193 @@
1
+ """Hermes directory plugin that mounts Taskforce Model Foundry tools.
2
+
3
+ Hermes discovers a directory plugin by ``plugin.yaml`` + a ``register(ctx)``
4
+ in this module, and tools reach the model only through
5
+ ``ctx.register_tool()`` -> ``tools.registry.register()``. The Foundry action
6
+ table lives in Node (``src/integrations/hermes.mjs``), so this module is a
7
+ thin mount: it asks the Node bridge for the adapter's own tool specs and
8
+ registers one handler per spec. Nothing is restated here, so an action added
9
+ on the Node side appears on Hermes without touching this file.
10
+
11
+ Resolution of the Foundry checkout, in order:
12
+ 1. ``TMF_FOUNDRY_ROOT``
13
+ 2. ``<plugin dir>/foundry`` (a copy or symlink placed next to the plugin)
14
+ 3. ``~/.hermes/taskforce-model-foundry``
15
+
16
+ Resolution of ``node``, in order: ``TMF_NODE``, then ``PATH``, then the usual
17
+ per-user/package locations (see ``_NODE_FALLBACKS``). The fallbacks exist
18
+ because a gateway started as a service does not inherit the login shell's
19
+ PATH, and without them a per-user node install makes the mount skip silently.
20
+
21
+ Registration never raises: a missing checkout or a broken bridge is reported
22
+ as a skipped mount, because a plugin that throws in ``register`` takes the
23
+ host's whole plugin load path down with it.
24
+ """
25
+
26
+ from __future__ import annotations
27
+
28
+ import json
29
+ import logging
30
+ import os
31
+ import shutil
32
+ import subprocess
33
+ from pathlib import Path
34
+ from typing import Any
35
+
36
+ logger = logging.getLogger(__name__)
37
+ TOOLSET = "taskforce_model_foundry"
38
+ _BRIDGE = Path(__file__).resolve().parent / "bridge.mjs"
39
+ _TIMEOUT_SPECS = 30
40
+ _TIMEOUT_CALL = 1800
41
+
42
+
43
+ def _foundry_root() -> Path | None:
44
+ candidates = []
45
+ env = os.environ.get("TMF_FOUNDRY_ROOT")
46
+ if env:
47
+ candidates.append(Path(env).expanduser())
48
+ candidates.append(_BRIDGE.parent / "foundry")
49
+ candidates.append(Path.home() / ".hermes" / "taskforce-model-foundry")
50
+ for candidate in candidates:
51
+ if (candidate / "src" / "integrations" / "hermes.mjs").is_file():
52
+ return candidate.resolve()
53
+ return None
54
+
55
+
56
+ # A gateway started as a systemd service inherits a cropped PATH, not the
57
+ # login shell's, so a per-user node (nvm, ~/.local/bin) is invisible to the
58
+ # plugin even though the operator can run `node` interactively. Looking in the
59
+ # usual per-user and package locations turns that silent skipped mount into a
60
+ # working one; TMF_NODE stays available for anything unusual.
61
+ _NODE_FALLBACKS = (
62
+ "~/.local/bin/node",
63
+ "/usr/local/bin/node",
64
+ "/opt/homebrew/bin/node",
65
+ "/usr/bin/node",
66
+ )
67
+
68
+
69
+ def _node() -> str | None:
70
+ override = os.environ.get("TMF_NODE")
71
+ if override:
72
+ candidate = Path(override).expanduser()
73
+ return str(candidate) if os.access(candidate, os.X_OK) else None
74
+ found = shutil.which("node") or shutil.which("nodejs")
75
+ if found:
76
+ return found
77
+ for raw in _NODE_FALLBACKS:
78
+ candidate = Path(raw).expanduser()
79
+ if os.access(candidate, os.X_OK):
80
+ return str(candidate)
81
+ return None
82
+
83
+
84
+ def _run_bridge(root: Path, args: list[str], timeout: int) -> dict[str, Any]:
85
+ node = _node()
86
+ if node is None:
87
+ override = os.environ.get("TMF_NODE")
88
+ detail = (
89
+ f"TMF_NODE={override} is not an executable"
90
+ if override
91
+ else "node is not on PATH (a gateway run as a service does not "
92
+ "inherit the login shell's PATH); set TMF_NODE to an absolute "
93
+ "node path, or add node's directory to the gateway's PATH"
94
+ )
95
+ return {"ok": False, "code": "node-unavailable", "error": detail}
96
+ env = dict(os.environ)
97
+ env["TMF_FOUNDRY_ROOT"] = str(root)
98
+ try:
99
+ proc = subprocess.run(
100
+ [node, str(_BRIDGE), *args],
101
+ capture_output=True,
102
+ text=True,
103
+ timeout=timeout,
104
+ env=env,
105
+ )
106
+ except subprocess.TimeoutExpired:
107
+ return {"ok": False, "code": "bridge-timeout", "error": f"bridge timed out after {timeout}s"}
108
+ line = ""
109
+ for candidate in reversed(proc.stdout.splitlines()):
110
+ if candidate.strip():
111
+ line = candidate.strip()
112
+ break
113
+ if not line:
114
+ return {
115
+ "ok": False,
116
+ "code": "bridge-no-output",
117
+ "error": (proc.stderr or "").strip()[:2000] or f"exit {proc.returncode} with no output",
118
+ }
119
+ try:
120
+ return json.loads(line)
121
+ except json.JSONDecodeError as err:
122
+ return {"ok": False, "code": "bridge-bad-json", "error": f"{err}: {line[:500]}"}
123
+
124
+
125
+ def _make_handler(root: Path, tool_name: str):
126
+ def handler(args: Any = None, **kwargs: Any) -> str:
127
+ # Hosts differ: some dispatch handler(args_dict), others handler(**kwargs).
128
+ # Accept both and merge, keeping explicit keywords authoritative.
129
+ payload: dict[str, Any] = {}
130
+ if isinstance(args, dict):
131
+ payload.update(args)
132
+ payload.update(kwargs)
133
+ result = _run_bridge(root, ["call", tool_name, json.dumps(payload)], _TIMEOUT_CALL)
134
+ envelope = result.get("envelope") if isinstance(result, dict) else None
135
+ if isinstance(envelope, dict) and isinstance(envelope.get("content"), str):
136
+ return envelope["content"]
137
+ return json.dumps(result, ensure_ascii=False)
138
+
139
+ handler.__name__ = f"tmf_handler_{tool_name}"
140
+ return handler
141
+
142
+
143
+ def _log(ctx, message: str) -> None:
144
+ """Report a mount decision without assuming the host exposes ``ctx.log``.
145
+
146
+ Hosts differ on whether ``PluginContext`` carries a ``log`` helper, and a
147
+ missing attribute here would raise out of ``register`` and make the host
148
+ roll back every tool this plugin just registered.
149
+ """
150
+ hook = getattr(ctx, "log", None)
151
+ if callable(hook):
152
+ try:
153
+ hook(message)
154
+ return
155
+ except Exception: # pragma: no cover - host logger misbehaving
156
+ pass
157
+ logger.info("%s", message)
158
+
159
+
160
+ def register(ctx) -> None:
161
+ root = _foundry_root()
162
+ if root is None:
163
+ _log(ctx,
164
+ "taskforce-model-foundry: no Foundry checkout found "
165
+ "(set TMF_FOUNDRY_ROOT or place it at <plugin>/foundry); no tools registered"
166
+ )
167
+ return
168
+ probe = _run_bridge(root, ["specs"], _TIMEOUT_SPECS)
169
+ if not probe.get("ok"):
170
+ _log(ctx,
171
+ "taskforce-model-foundry: adapter probe failed "
172
+ f"({probe.get('code')}: {probe.get('error')}); no tools registered"
173
+ )
174
+ return
175
+ registered = 0
176
+ for spec in probe.get("specs") or []:
177
+ fn = spec.get("function") if isinstance(spec, dict) else None
178
+ if not isinstance(fn, dict) or not fn.get("name"):
179
+ continue
180
+ name = fn["name"]
181
+ ctx.register_tool(
182
+ name=name,
183
+ toolset=TOOLSET,
184
+ schema=fn.get("parameters") or {"type": "object", "properties": {}},
185
+ handler=_make_handler(root, name),
186
+ description=fn.get("description", ""),
187
+ emoji="🏭",
188
+ )
189
+ registered += 1
190
+ _log(ctx,
191
+ f"taskforce-model-foundry: registered {registered} tool(s) from {root} "
192
+ f"(contract {probe.get('contractVersion')})"
193
+ )
@@ -0,0 +1,46 @@
1
+ #!/usr/bin/env node
2
+ // Node side of the Hermes Python-plugin bridge.
3
+ //
4
+ // Hermes discovers directory plugins written in Python, but the Foundry
5
+ // adapter is the Node module src/integrations/hermes.mjs. Rather than
6
+ // restate the action table in Python, this bridge exposes exactly two
7
+ // line-oriented commands over the existing adapter, so adding an action in
8
+ // src/integrations/openclaw.mjs still surfaces it on Hermes:
9
+ //
10
+ // specs -> prints {"ok":true,"specs":[...openai function specs]}
11
+ // call <tool> <json-args> -> prints the adapter envelope as JSON
12
+ //
13
+ // Every outcome is JSON on stdout with a boolean `ok`; the process never
14
+ // exits non-zero for a tool-level failure, because the Python side has to
15
+ // hand the model readable text either way.
16
+
17
+ const FOUNDRY = process.env.TMF_FOUNDRY_ROOT || new URL('../../../', import.meta.url).pathname;
18
+
19
+ function out(obj) {
20
+ process.stdout.write(`${JSON.stringify(obj)}\n`);
21
+ }
22
+
23
+ async function main() {
24
+ const [cmd, ...rest] = process.argv.slice(2);
25
+ let hermes;
26
+ try {
27
+ hermes = await import(new URL('src/integrations/hermes.mjs', `file://${FOUNDRY.replace(/\/?$/, '/')}`).href);
28
+ } catch (err) {
29
+ out({ ok: false, code: 'adapter-unavailable', error: String(err && err.message || err), foundryRoot: FOUNDRY });
30
+ return;
31
+ }
32
+ if (cmd === 'specs') {
33
+ out({ ok: true, host: hermes.HOST, contractVersion: hermes.CONTRACT_VERSION, specs: hermes.toolSpecs() });
34
+ return;
35
+ }
36
+ if (cmd === 'call') {
37
+ const [tool, argsJson] = rest;
38
+ const adapter = hermes.createHermesAdapter({ baseDir: process.env.TMF_WORKSPACE || process.cwd() });
39
+ const envelope = await adapter.callTool(tool, argsJson === undefined ? '{}' : argsJson);
40
+ out({ ok: envelope.ok !== false, envelope });
41
+ return;
42
+ }
43
+ out({ ok: false, code: 'unknown-bridge-command', error: `unknown command: ${String(cmd)}` });
44
+ }
45
+
46
+ main().catch((err) => out({ ok: false, code: 'bridge-crash', error: String(err && err.message || err) }));
@@ -0,0 +1,7 @@
1
+ name: taskforce-model-foundry
2
+ version: 0.1.0
3
+ description: Taskforce Model Foundry tools (synthesize, train, evaluate, export) for Hermes.
4
+ author: Taskforce
5
+ manifest_version: 2
6
+ api_version: 1
7
+ hooks: []
@@ -0,0 +1,230 @@
1
+ """Host-compatibility regression tests for the Hermes directory plugin.
2
+
3
+ Two real breakages found while mounting this plugin on a live Hermes host are
4
+ pinned here, because both surfaced only at dispatch/registration time and
5
+ neither is visible from the Node side of the adapter:
6
+
7
+ 1. ``tools.registry.dispatch`` calls ``entry.handler(args, **kwargs)`` with
8
+ the argument dict *positionally*, while other hosts call
9
+ ``handler(**kwargs)``. A keyword-only handler raised ``TypeError`` on the
10
+ very first dispatch even though registration had succeeded.
11
+ 2. ``PluginContext`` does not always carry a ``log`` helper, and an
12
+ ``AttributeError`` raised out of ``register`` makes the host roll back
13
+ every tool the plugin just registered.
14
+
15
+ The Node bridge is stubbed: these tests are about the Python mount contract,
16
+ not about Foundry actions (those are covered by test/integration-hermes.test.mjs).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import json
22
+ import os
23
+ import stat
24
+ import sys
25
+ import tempfile
26
+ import unittest
27
+ from pathlib import Path
28
+ from unittest import mock
29
+
30
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
31
+
32
+ import taskforce_model_foundry as plugin # noqa: E402
33
+
34
+
35
+ SPECS = {
36
+ "ok": True,
37
+ "contractVersion": "test",
38
+ "specs": [
39
+ {
40
+ "function": {
41
+ "name": "tmf_status",
42
+ "description": "status",
43
+ "parameters": {"type": "object", "properties": {"jobId": {"type": "string"}}},
44
+ }
45
+ },
46
+ {"function": {"name": "tmf_doctor", "description": "doctor", "parameters": {}}},
47
+ {"not_a_function": True},
48
+ ],
49
+ }
50
+
51
+
52
+ class RecordingBridge:
53
+ """Stands in for ``_run_bridge`` and records every invocation."""
54
+
55
+ def __init__(self, specs=None):
56
+ self.calls = []
57
+ self._specs = specs if specs is not None else SPECS
58
+
59
+ def __call__(self, root, args, timeout):
60
+ self.calls.append({"root": root, "args": list(args), "timeout": timeout})
61
+ if args[:1] == ["specs"]:
62
+ return self._specs
63
+ return {"ok": True, "envelope": {"content": "bridge-content"}}
64
+
65
+
66
+ class CtxWithoutLog:
67
+ """A host context that exposes only ``register_tool`` (no ``log``)."""
68
+
69
+ def __init__(self):
70
+ self.tools = {}
71
+
72
+ def register_tool(self, *, name, toolset, schema, handler, description="", emoji=""):
73
+ self.tools[name] = {
74
+ "toolset": toolset,
75
+ "schema": schema,
76
+ "handler": handler,
77
+ "description": description,
78
+ "emoji": emoji,
79
+ }
80
+
81
+
82
+ class CtxWithLog(CtxWithoutLog):
83
+ def __init__(self):
84
+ super().__init__()
85
+ self.messages = []
86
+
87
+ def log(self, message):
88
+ self.messages.append(message)
89
+
90
+
91
+ class PluginMountTest(unittest.TestCase):
92
+ def setUp(self):
93
+ self._real_bridge = plugin._run_bridge
94
+ self._real_root = plugin._foundry_root
95
+ self.bridge = RecordingBridge()
96
+ plugin._run_bridge = self.bridge
97
+ plugin._foundry_root = lambda: Path("/fake/foundry")
98
+
99
+ def tearDown(self):
100
+ plugin._run_bridge = self._real_bridge
101
+ plugin._foundry_root = self._real_root
102
+
103
+ def _register(self, ctx):
104
+ plugin.register(ctx)
105
+ return ctx
106
+
107
+ def test_register_without_ctx_log(self):
108
+ ctx = self._register(CtxWithoutLog())
109
+ self.assertEqual(sorted(ctx.tools), ["tmf_doctor", "tmf_status"])
110
+ self.assertEqual(ctx.tools["tmf_status"]["toolset"], plugin.TOOLSET)
111
+
112
+ def test_dispatch_conventions_agree(self):
113
+ ctx = self._register(CtxWithoutLog())
114
+ handler = ctx.tools["tmf_status"]["handler"]
115
+
116
+ self.bridge.calls.clear()
117
+ positional = handler({"jobId": "job-1"})
118
+ keyword = handler(jobId="job-1")
119
+
120
+ self.assertEqual(positional, "bridge-content")
121
+ self.assertEqual(keyword, "bridge-content")
122
+ self.assertEqual(len(self.bridge.calls), 2)
123
+ payloads = [json.loads(call["args"][2]) for call in self.bridge.calls]
124
+ self.assertEqual(payloads[0], {"jobId": "job-1"})
125
+ self.assertEqual(payloads[0], payloads[1])
126
+ self.assertEqual(self.bridge.calls[0]["args"][:2], ["call", "tmf_status"])
127
+
128
+ def test_no_arg_dispatch_sends_empty_payload(self):
129
+ ctx = self._register(CtxWithoutLog())
130
+ self.bridge.calls.clear()
131
+ ctx.tools["tmf_doctor"]["handler"]()
132
+ self.assertEqual(json.loads(self.bridge.calls[0]["args"][2]), {})
133
+
134
+ def test_explicit_keywords_win_over_positional_dict(self):
135
+ ctx = self._register(CtxWithoutLog())
136
+ handler = ctx.tools["tmf_status"]["handler"]
137
+ self.bridge.calls.clear()
138
+ handler({"jobId": "from-dict", "keep": 1}, jobId="from-kwargs")
139
+ self.assertEqual(
140
+ json.loads(self.bridge.calls[0]["args"][2]),
141
+ {"jobId": "from-kwargs", "keep": 1},
142
+ )
143
+
144
+ def test_non_envelope_result_is_returned_as_json(self):
145
+ ctx = self._register(CtxWithoutLog())
146
+ plugin._run_bridge = lambda root, args, timeout: {"ok": False, "code": "boom"}
147
+ out = ctx.tools["tmf_doctor"]["handler"]()
148
+ self.assertEqual(json.loads(out), {"ok": False, "code": "boom"})
149
+
150
+ def test_missing_checkout_registers_nothing_and_does_not_raise(self):
151
+ plugin._foundry_root = lambda: None
152
+ ctx = self._register(CtxWithLog())
153
+ self.assertEqual(ctx.tools, {})
154
+ self.assertTrue(any("no tools registered" in m for m in ctx.messages))
155
+
156
+ def test_failed_probe_registers_nothing_and_does_not_raise(self):
157
+ plugin._run_bridge = RecordingBridge(specs={"ok": False, "code": "bridge-timeout", "error": "x"})
158
+ ctx = self._register(CtxWithLog())
159
+ self.assertEqual(ctx.tools, {})
160
+ self.assertTrue(any("adapter probe failed" in m for m in ctx.messages))
161
+
162
+ def test_raising_ctx_log_does_not_break_registration(self):
163
+ class CtxBadLog(CtxWithoutLog):
164
+ def log(self, message):
165
+ raise RuntimeError("host logger down")
166
+
167
+ ctx = self._register(CtxBadLog())
168
+ self.assertEqual(sorted(ctx.tools), ["tmf_doctor", "tmf_status"])
169
+
170
+
171
+ class NodeResolutionTest(unittest.TestCase):
172
+ """A gateway run as a service has a cropped PATH, so node must still resolve.
173
+
174
+ This is the third live-host breakage: the plugin loaded, the registry scope
175
+ was right, and the toolset was empty, because ``shutil.which("node")``
176
+ found nothing under a service PATH while ``node -v`` worked in the
177
+ operator's shell. The symptom reaches the model as ``Unknown tool:
178
+ tmf_export``, which does not point at PATH at all, so the resolution order
179
+ and the message that explains it are pinned here.
180
+ """
181
+
182
+ def setUp(self):
183
+ self.tmp = tempfile.TemporaryDirectory()
184
+ self.addCleanup(self.tmp.cleanup)
185
+ self.fake_node = Path(self.tmp.name) / "node"
186
+ self.fake_node.write_text("#!/bin/sh\nexit 0\n")
187
+ self.fake_node.chmod(self.fake_node.stat().st_mode | stat.S_IXUSR)
188
+
189
+ def test_tmf_node_overrides_path(self):
190
+ with mock.patch.dict(os.environ, {"TMF_NODE": str(self.fake_node)}):
191
+ self.assertEqual(plugin._node(), str(self.fake_node))
192
+
193
+ def test_tmf_node_expands_user(self):
194
+ # Operators write ~/.local/bin/node; an unexpanded "~" would just miss.
195
+ with mock.patch.dict(os.environ, {"TMF_NODE": "~/node", "HOME": self.tmp.name}):
196
+ self.assertEqual(plugin._node(), str(self.fake_node))
197
+
198
+ def test_non_executable_tmf_node_is_rejected(self):
199
+ dud = Path(self.tmp.name) / "not-node"
200
+ dud.write_text("")
201
+ with mock.patch.dict(os.environ, {"TMF_NODE": str(dud)}):
202
+ self.assertIsNone(plugin._node())
203
+
204
+ def test_fallback_locations_are_tried_when_path_is_cropped(self):
205
+ env = dict(os.environ)
206
+ env.pop("TMF_NODE", None)
207
+ with mock.patch.dict(os.environ, env, clear=True), \
208
+ mock.patch.object(plugin.shutil, "which", return_value=None), \
209
+ mock.patch.object(plugin, "_NODE_FALLBACKS", ("/nope/node", str(self.fake_node))):
210
+ self.assertEqual(plugin._node(), str(self.fake_node))
211
+
212
+ def test_node_unavailable_error_names_tmf_node(self):
213
+ env = dict(os.environ)
214
+ env.pop("TMF_NODE", None)
215
+ with mock.patch.dict(os.environ, env, clear=True), \
216
+ mock.patch.object(plugin, "_node", return_value=None):
217
+ result = plugin._run_bridge(Path("/fake/foundry"), ["specs"], 1)
218
+ self.assertEqual(result["code"], "node-unavailable")
219
+ self.assertIn("TMF_NODE", result["error"])
220
+ self.assertIn("PATH", result["error"])
221
+
222
+ def test_bad_tmf_node_error_names_the_bad_value(self):
223
+ with mock.patch.dict(os.environ, {"TMF_NODE": "/nope/node"}):
224
+ result = plugin._run_bridge(Path("/fake/foundry"), ["specs"], 1)
225
+ self.assertEqual(result["code"], "node-unavailable")
226
+ self.assertIn("/nope/node", result["error"])
227
+
228
+
229
+ if __name__ == "__main__":
230
+ unittest.main()
@@ -0,0 +1,27 @@
1
+ // OpenClaw host plugin entry.
2
+ //
3
+ // The host discovers this file through `openclaw.extensions` in package.json
4
+ // plus the `openclaw.plugin.json` manifest at the package root. It is a thin
5
+ // wrapper: the tool list comes from ./tools.mjs, which forwards every call to
6
+ // the in-process adapter in src/integrations/openclaw.mjs, so the host surface
7
+ // cannot drift from the adapter contract or from the `tmf` CLI (both go
8
+ // through src/api.mjs).
9
+ //
10
+ // Naming: adapter action `train` is published as tool `tmf_train`, matching
11
+ // `contracts.tools` in openclaw.plugin.json.
12
+
13
+ import { defineToolPlugin } from 'openclaw/plugin-sdk/tool-plugin';
14
+
15
+ import { CONTRACT_VERSION } from '../../src/integrations/openclaw.mjs';
16
+ import { buildTools } from './tools.mjs';
17
+
18
+ export { PARAM_SCHEMA, TOOL_PREFIX, buildTools, parametersFor, toolNameFor } from './tools.mjs';
19
+
20
+ export const PLUGIN_ID = 'taskforce-model-foundry';
21
+
22
+ export default defineToolPlugin({
23
+ id: PLUGIN_ID,
24
+ name: 'Taskforce Model Foundry',
25
+ description: `Taskforce Model Foundry tools (contract v${CONTRACT_VERSION}).`,
26
+ tools: (tool, ctx) => buildTools(tool, { config: ctx?.config ?? {} }),
27
+ });
@@ -0,0 +1,70 @@
1
+ // Tool surface for the OpenClaw host plugin, kept free of any `openclaw`
2
+ // import so the package's own test suite can assert it without the host
3
+ // package installed. index.mjs adds nothing but the host registration.
4
+
5
+ import { ACTION_SPECS, createOpenClawAdapter } from '../../src/integrations/openclaw.mjs';
6
+
7
+ /** JSON Schema fragment per adapter param. Keyed by param name, not action. */
8
+ export const PARAM_SCHEMA = {
9
+ configFile: { type: 'string', description: 'Foundry config file path.' },
10
+ requireConfig: { type: 'boolean', description: 'Fail when no config file is present.' },
11
+ jobId: { type: 'string', description: 'Durable foundry job id.' },
12
+ auditTail: { type: 'number', description: 'How many audit-log lines to return.' },
13
+ outDir: { type: 'string', description: 'Output directory.' },
14
+ seed: { type: 'number', description: 'Deterministic seed.' },
15
+ count: { type: 'number', description: 'Number of synthetic records to write.' },
16
+ profile: { type: 'string', description: 'Synthetic corpus profile name.' },
17
+ resume: { type: 'boolean', description: 'Resume an interrupted training job.' },
18
+ resumeCancelled: { type: 'boolean', description: 'Resume a cancelled training job.' },
19
+ auditEveryStep: { type: 'boolean', description: 'Append an audit entry per training step.' },
20
+ gates: { type: 'string', description: 'Evaluation gate expression.' },
21
+ reportFile: { type: 'string', description: 'Where to write the evaluation report.' },
22
+ maxNewTokens: { type: 'number', description: 'Generation budget per eval sample.' },
23
+ evalReport: { type: 'string', description: 'Evaluation report consumed by export.' },
24
+ version: { type: 'string', description: 'Export version label.' },
25
+ evaluateIfMissing: { type: 'boolean', description: 'Run evaluation when no report exists.' },
26
+ };
27
+
28
+ export const TOOL_PREFIX = 'tmf_';
29
+
30
+ /** `tmf_train` -> `train`; exported so the host test can assert the mapping. */
31
+ export function toolNameFor(action) {
32
+ return `${TOOL_PREFIX}${action}`;
33
+ }
34
+
35
+ export function parametersFor(action) {
36
+ const spec = ACTION_SPECS[action];
37
+ const properties = {};
38
+ for (const param of spec.params) {
39
+ const schema = PARAM_SCHEMA[param];
40
+ if (!schema) throw new Error(`no JSON schema declared for param "${param}" of action "${action}"`);
41
+ properties[param] = schema;
42
+ }
43
+ return {
44
+ type: 'object',
45
+ additionalProperties: false,
46
+ properties,
47
+ ...(spec.required?.length ? { required: [...spec.required] } : {}),
48
+ };
49
+ }
50
+
51
+ /**
52
+ * Build the tool list from the adapter's own action table so adding an action
53
+ * in the adapter publishes it here too.
54
+ */
55
+ export function buildTools(tool, { config = {} } = {}) {
56
+ const adapter = createOpenClawAdapter({
57
+ baseDir: config.baseDir ?? process.cwd(),
58
+ configFile: config.configFile ?? null,
59
+ allowCompute: config.allowCompute ?? true,
60
+ });
61
+ return Object.keys(ACTION_SPECS).map((action) =>
62
+ tool({
63
+ name: toolNameFor(action),
64
+ description: ACTION_SPECS[action].summary,
65
+ parameters: parametersFor(action),
66
+ execute: async (params) => adapter.invoke(action, params ?? {}),
67
+ }),
68
+ );
69
+ }
70
+
@@ -0,0 +1,24 @@
1
+ {
2
+ "id": "taskforce-model-foundry",
3
+ "name": "Taskforce Model Foundry",
4
+ "description": "Taskforce Model Foundry tools (contract v1).",
5
+ "version": "0.1.0",
6
+ "configSchema": {
7
+ "type": "object",
8
+ "properties": {},
9
+ "additionalProperties": false
10
+ },
11
+ "activation": {
12
+ "onStartup": true
13
+ },
14
+ "contracts": {
15
+ "tools": [
16
+ "tmf_doctor",
17
+ "tmf_status",
18
+ "tmf_synthesize",
19
+ "tmf_train",
20
+ "tmf_evaluate",
21
+ "tmf_export"
22
+ ]
23
+ }
24
+ }
package/package.json CHANGED
@@ -1,6 +1,72 @@
1
1
  {
2
2
  "name": "taskforce-model-foundry",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
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
+ "type": "module",
6
+ "license": "MIT",
7
+ "engines": {
8
+ "node": ">=20.0.0"
9
+ },
10
+ "bin": {
11
+ "tmf": "bin/tmf.mjs"
12
+ },
13
+ "main": "src/index.mjs",
14
+ "exports": {
15
+ ".": "./src/index.mjs",
16
+ "./api": "./src/api.mjs",
17
+ "./integrations/openclaw": "./src/integrations/openclaw.mjs",
18
+ "./integrations/openclaw-plugin": "./integrations/openclaw-plugin/index.mjs",
19
+ "./integrations/openclaw-plugin/tools": "./integrations/openclaw-plugin/tools.mjs",
20
+ "./integrations/hermes": "./src/integrations/hermes.mjs",
21
+ "./package.json": "./package.json"
22
+ },
23
+ "files": [
24
+ "bin/",
25
+ "src/",
26
+ "docs/",
27
+ "openclaw.plugin.json",
28
+ "integrations/openclaw-plugin/",
29
+ "integrations/hermes-plugin/",
30
+ "scripts/e2e-demo.sh",
31
+ "README.md",
32
+ "package.json",
33
+ "!docs/reports",
34
+ "!**/__pycache__",
35
+ "!**/*.pyc"
36
+ ],
37
+ "scripts": {
38
+ "test": "node --test \"test/**/*.test.mjs\"",
39
+ "demo": "bash scripts/e2e-demo.sh",
40
+ "doctor": "node bin/tmf.mjs doctor"
41
+ },
42
+ "dependencies": {},
43
+ "repository": {
44
+ "type": "git",
45
+ "url": "git+https://github.com/ambitioncn/taskforce-model-foundry.git"
46
+ },
47
+ "keywords": [
48
+ "llm",
49
+ "post-training",
50
+ "lora",
51
+ "fine-tuning",
52
+ "openclaw",
53
+ "hermes",
54
+ "model-foundry"
55
+ ],
56
+ "openclaw": {
57
+ "extensions": [
58
+ "./integrations/openclaw-plugin/index.mjs"
59
+ ],
60
+ "compat": {
61
+ "pluginApi": ">=2026.5.17"
62
+ }
63
+ },
64
+ "peerDependencies": {
65
+ "openclaw": ">=2026.5.17"
66
+ },
67
+ "peerDependenciesMeta": {
68
+ "openclaw": {
69
+ "optional": true
70
+ }
71
+ }
72
+ }