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,115 @@
|
|
|
1
|
+
// Normalization and quality filtering.
|
|
2
|
+
|
|
3
|
+
// Built with new RegExp so the source stays plain ASCII.
|
|
4
|
+
const CONTROL_CHARS = new RegExp('[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]', 'g');
|
|
5
|
+
// Non-global twin: `.test` on a global regex would advance lastIndex.
|
|
6
|
+
const NON_PRINTABLE = new RegExp('[\\u0000-\\u0008\\u000b\\u000c\\u000e-\\u001f\\u007f]');
|
|
7
|
+
const ZERO_WIDTH = new RegExp('[\\u200b-\\u200f\\u2028\\u2029\\u2060\\ufeff]', 'g');
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_CLEAN_CONFIG = {
|
|
10
|
+
normalizeUnicode: 'NFKC',
|
|
11
|
+
collapseWhitespace: true,
|
|
12
|
+
stripControlChars: true,
|
|
13
|
+
trim: true,
|
|
14
|
+
lowercase: false,
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
export function cleanText(text, config = {}) {
|
|
18
|
+
const cfg = { ...DEFAULT_CLEAN_CONFIG, ...config };
|
|
19
|
+
let value = String(text ?? '');
|
|
20
|
+
const applied = [];
|
|
21
|
+
if (cfg.normalizeUnicode) {
|
|
22
|
+
const normalized = value.normalize(cfg.normalizeUnicode);
|
|
23
|
+
if (normalized !== value) applied.push('unicode');
|
|
24
|
+
value = normalized;
|
|
25
|
+
}
|
|
26
|
+
if (cfg.stripControlChars) {
|
|
27
|
+
CONTROL_CHARS.lastIndex = 0;
|
|
28
|
+
ZERO_WIDTH.lastIndex = 0;
|
|
29
|
+
const stripped = value.replace(CONTROL_CHARS, '').replace(ZERO_WIDTH, '');
|
|
30
|
+
if (stripped !== value) applied.push('control_chars');
|
|
31
|
+
value = stripped;
|
|
32
|
+
}
|
|
33
|
+
if (cfg.collapseWhitespace) {
|
|
34
|
+
// Preserve paragraph structure but drop runs of spaces/tabs and 3+ newlines.
|
|
35
|
+
const collapsed = value.replace(/[ \t]+/g, ' ').replace(/ ?\n ?/g, '\n').replace(/\n{3,}/g, '\n\n');
|
|
36
|
+
if (collapsed !== value) applied.push('whitespace');
|
|
37
|
+
value = collapsed;
|
|
38
|
+
}
|
|
39
|
+
if (cfg.lowercase) {
|
|
40
|
+
const lowered = value.toLowerCase();
|
|
41
|
+
if (lowered !== value) applied.push('lowercase');
|
|
42
|
+
value = lowered;
|
|
43
|
+
}
|
|
44
|
+
if (cfg.trim) {
|
|
45
|
+
const trimmed = value.trim();
|
|
46
|
+
if (trimmed !== value) applied.push('trim');
|
|
47
|
+
value = trimmed;
|
|
48
|
+
}
|
|
49
|
+
return { text: value, applied };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Normalized key for exact-duplicate and leakage comparison. Deliberately more
|
|
53
|
+
// aggressive than cleanText: case and punctuation are flattened so cosmetic
|
|
54
|
+
// edits cannot smuggle a holdout sample into the training set.
|
|
55
|
+
export function canonicalKey(text) {
|
|
56
|
+
return String(text ?? '')
|
|
57
|
+
.normalize('NFKC')
|
|
58
|
+
.toLowerCase()
|
|
59
|
+
.replace(/[^\p{L}\p{N}]+/gu, ' ')
|
|
60
|
+
.trim();
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export const DEFAULT_QUALITY_CONFIG = {
|
|
64
|
+
minChars: 8,
|
|
65
|
+
maxChars: 4000,
|
|
66
|
+
maxRepeatRatio: 0.35,
|
|
67
|
+
minAlnumRatio: 0.45,
|
|
68
|
+
maxNonPrintableRatio: 0.01,
|
|
69
|
+
rejectPlaceholders: ['lorem ipsum', 'todo', 'tbd', 'xxxxx'],
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
export function qualityReport(text, config = {}) {
|
|
73
|
+
const cfg = { ...DEFAULT_QUALITY_CONFIG, ...config };
|
|
74
|
+
const value = String(text ?? '');
|
|
75
|
+
const chars = [...value];
|
|
76
|
+
const reasons = [];
|
|
77
|
+
|
|
78
|
+
if (chars.length < cfg.minChars) reasons.push(`too_short(${chars.length}<${cfg.minChars})`);
|
|
79
|
+
if (chars.length > cfg.maxChars) reasons.push(`too_long(${chars.length}>${cfg.maxChars})`);
|
|
80
|
+
|
|
81
|
+
const alnum = chars.filter((c) => /[\p{L}\p{N}]/u.test(c)).length;
|
|
82
|
+
const alnumRatio = chars.length ? alnum / chars.length : 0;
|
|
83
|
+
if (chars.length >= cfg.minChars && alnumRatio < cfg.minAlnumRatio) {
|
|
84
|
+
reasons.push(`low_alnum_ratio(${alnumRatio.toFixed(2)}<${cfg.minAlnumRatio})`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const nonPrintable = chars.filter((c) => NON_PRINTABLE.test(c)).length;
|
|
88
|
+
const nonPrintableRatio = chars.length ? nonPrintable / chars.length : 0;
|
|
89
|
+
if (nonPrintableRatio > cfg.maxNonPrintableRatio) {
|
|
90
|
+
reasons.push(`non_printable(${nonPrintableRatio.toFixed(3)}>${cfg.maxNonPrintableRatio})`);
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Repetition: share of the text taken by its most common 4-gram.
|
|
94
|
+
let repeatRatio = 0;
|
|
95
|
+
if (chars.length >= 16) {
|
|
96
|
+
const counts = new Map();
|
|
97
|
+
for (let i = 0; i + 4 <= chars.length; i += 1) {
|
|
98
|
+
const gram = chars.slice(i, i + 4).join('');
|
|
99
|
+
counts.set(gram, (counts.get(gram) ?? 0) + 1);
|
|
100
|
+
}
|
|
101
|
+
const total = chars.length - 3;
|
|
102
|
+
const max = Math.max(...counts.values());
|
|
103
|
+
repeatRatio = max / total;
|
|
104
|
+
if (repeatRatio > cfg.maxRepeatRatio) reasons.push(`repetitive(${repeatRatio.toFixed(2)}>${cfg.maxRepeatRatio})`);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const lower = value.toLowerCase();
|
|
108
|
+
const placeholder = cfg.rejectPlaceholders.find((p) => lower.includes(p));
|
|
109
|
+
if (placeholder) reasons.push(`placeholder(${placeholder})`);
|
|
110
|
+
|
|
111
|
+
const score = Number(
|
|
112
|
+
Math.max(0, Math.min(1, 0.5 * alnumRatio + 0.5 * (1 - Math.min(1, repeatRatio / Math.max(cfg.maxRepeatRatio, 1e-6))))).toFixed(4),
|
|
113
|
+
);
|
|
114
|
+
return { ok: reasons.length === 0, reasons, score, metrics: { chars: chars.length, alnumRatio, repeatRatio, nonPrintableRatio } };
|
|
115
|
+
}
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// Exact and near-duplicate detection.
|
|
2
|
+
//
|
|
3
|
+
// Exact duplicates are caught on the canonical key. Near duplicates use MinHash
|
|
4
|
+
// over character shingles with LSH banding, so the comparison count stays
|
|
5
|
+
// linear instead of quadratic as a corpus grows.
|
|
6
|
+
|
|
7
|
+
import { sha256 } from '../core/hash.mjs';
|
|
8
|
+
import { canonicalKey } from './clean.mjs';
|
|
9
|
+
|
|
10
|
+
export const DEFAULT_DEDUPE_CONFIG = {
|
|
11
|
+
nearDuplicates: true,
|
|
12
|
+
shingleSize: 5,
|
|
13
|
+
numHashes: 64,
|
|
14
|
+
bands: 16,
|
|
15
|
+
threshold: 0.85,
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function hash32(str, seed) {
|
|
19
|
+
let h = seed >>> 0;
|
|
20
|
+
for (let i = 0; i < str.length; i += 1) {
|
|
21
|
+
h ^= str.charCodeAt(i);
|
|
22
|
+
h = Math.imul(h, 0x01000193) >>> 0;
|
|
23
|
+
}
|
|
24
|
+
// Final avalanche so the seeded hashes decorrelate.
|
|
25
|
+
h ^= h >>> 16;
|
|
26
|
+
h = Math.imul(h, 0x7feb352d) >>> 0;
|
|
27
|
+
h ^= h >>> 15;
|
|
28
|
+
return h >>> 0;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function shingles(text, size) {
|
|
32
|
+
const key = canonicalKey(text);
|
|
33
|
+
const chars = [...key];
|
|
34
|
+
if (chars.length <= size) return new Set([key]);
|
|
35
|
+
const out = new Set();
|
|
36
|
+
for (let i = 0; i + size <= chars.length; i += 1) out.add(chars.slice(i, i + size).join(''));
|
|
37
|
+
return out;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function minhashSignature(text, { shingleSize, numHashes } = DEFAULT_DEDUPE_CONFIG) {
|
|
41
|
+
const grams = shingles(text, shingleSize);
|
|
42
|
+
const sig = new Uint32Array(numHashes).fill(0xffffffff);
|
|
43
|
+
for (const gram of grams) {
|
|
44
|
+
for (let h = 0; h < numHashes; h += 1) {
|
|
45
|
+
const v = hash32(gram, (0x9e3779b9 + h * 0x85ebca6b) >>> 0);
|
|
46
|
+
if (v < sig[h]) sig[h] = v;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return sig;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function signatureSimilarity(a, b) {
|
|
53
|
+
let same = 0;
|
|
54
|
+
for (let i = 0; i < a.length; i += 1) if (a[i] === b[i]) same += 1;
|
|
55
|
+
return same / a.length;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function jaccard(textA, textB, shingleSize = DEFAULT_DEDUPE_CONFIG.shingleSize) {
|
|
59
|
+
const a = shingles(textA, shingleSize);
|
|
60
|
+
const b = shingles(textB, shingleSize);
|
|
61
|
+
let inter = 0;
|
|
62
|
+
for (const g of a) if (b.has(g)) inter += 1;
|
|
63
|
+
const union = a.size + b.size - inter;
|
|
64
|
+
return union === 0 ? 1 : inter / union;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function bandKeys(sig, bands) {
|
|
68
|
+
const rows = Math.floor(sig.length / bands);
|
|
69
|
+
const keys = [];
|
|
70
|
+
for (let b = 0; b < bands; b += 1) {
|
|
71
|
+
const slice = Array.from(sig.subarray(b * rows, (b + 1) * rows)).join(',');
|
|
72
|
+
keys.push(`${b}:${hash32(slice, 0x1b873593)}`);
|
|
73
|
+
}
|
|
74
|
+
return keys;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class NearDuplicateIndex {
|
|
78
|
+
constructor(config = {}) {
|
|
79
|
+
this.config = { ...DEFAULT_DEDUPE_CONFIG, ...config };
|
|
80
|
+
if (this.config.numHashes % this.config.bands !== 0) {
|
|
81
|
+
throw new Error(`numHashes ${this.config.numHashes} must be divisible by bands ${this.config.bands}`);
|
|
82
|
+
}
|
|
83
|
+
this.buckets = new Map();
|
|
84
|
+
this.entries = [];
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
// Closest already-indexed entry at or above threshold, else null.
|
|
88
|
+
query(text) {
|
|
89
|
+
const sig = minhashSignature(text, this.config);
|
|
90
|
+
const candidates = new Set();
|
|
91
|
+
for (const key of bandKeys(sig, this.config.bands)) {
|
|
92
|
+
for (const idx of this.buckets.get(key) ?? []) candidates.add(idx);
|
|
93
|
+
}
|
|
94
|
+
let best = null;
|
|
95
|
+
for (const idx of candidates) {
|
|
96
|
+
const entry = this.entries[idx];
|
|
97
|
+
const approx = signatureSimilarity(sig, entry.sig);
|
|
98
|
+
// Confirm LSH candidates with exact Jaccard so banding cannot force a merge.
|
|
99
|
+
const exact = jaccard(text, entry.text, this.config.shingleSize);
|
|
100
|
+
if (exact >= this.config.threshold && (!best || exact > best.similarity)) {
|
|
101
|
+
best = { id: entry.id, similarity: exact, approximate: approx };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return { signature: sig, match: best };
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
add(id, text, signature) {
|
|
108
|
+
const sig = signature ?? minhashSignature(text, this.config);
|
|
109
|
+
const idx = this.entries.length;
|
|
110
|
+
this.entries.push({ id, text, sig });
|
|
111
|
+
for (const key of bandKeys(sig, this.config.bands)) {
|
|
112
|
+
if (!this.buckets.has(key)) this.buckets.set(key, []);
|
|
113
|
+
this.buckets.get(key).push(idx);
|
|
114
|
+
}
|
|
115
|
+
return idx;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
get size() {
|
|
119
|
+
return this.entries.length;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
export function exactKey(text) {
|
|
124
|
+
return sha256(canonicalKey(text));
|
|
125
|
+
}
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
// Local-only ingestion of private data.
|
|
2
|
+
//
|
|
3
|
+
// Nothing here reaches the network: a dataset is a path on this machine. The
|
|
4
|
+
// loader understands JSONL, plain text and CSV, and attaches provenance to each
|
|
5
|
+
// record as it is read.
|
|
6
|
+
|
|
7
|
+
import { readFile, stat, readdir } from 'node:fs/promises';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { sha256 } from '../core/hash.mjs';
|
|
10
|
+
import { normalizeDatasetDescriptor, sourceRecord } from './provenance.mjs';
|
|
11
|
+
|
|
12
|
+
const TEXT_EXTENSIONS = new Set(['.txt', '.md']);
|
|
13
|
+
const JSONL_EXTENSIONS = new Set(['.jsonl', '.ndjson']);
|
|
14
|
+
const CSV_EXTENSIONS = new Set(['.csv', '.tsv']);
|
|
15
|
+
|
|
16
|
+
function detectFormat(file, declared) {
|
|
17
|
+
if (declared && declared !== 'auto') return declared;
|
|
18
|
+
const ext = path.extname(file).toLowerCase();
|
|
19
|
+
if (JSONL_EXTENSIONS.has(ext)) return 'jsonl';
|
|
20
|
+
if (CSV_EXTENSIONS.has(ext)) return 'csv';
|
|
21
|
+
if (TEXT_EXTENSIONS.has(ext)) return 'text';
|
|
22
|
+
if (ext === '.json') return 'json';
|
|
23
|
+
throw new Error(`cannot infer format for "${file}"; set dataset.format explicitly`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Minimal RFC4180-ish parser: quoted fields, doubled quotes, embedded newlines.
|
|
27
|
+
export function parseDelimited(content, delimiter) {
|
|
28
|
+
const rows = [];
|
|
29
|
+
let row = [];
|
|
30
|
+
let field = '';
|
|
31
|
+
let quoted = false;
|
|
32
|
+
for (let i = 0; i < content.length; i += 1) {
|
|
33
|
+
const ch = content[i];
|
|
34
|
+
if (quoted) {
|
|
35
|
+
if (ch === '"') {
|
|
36
|
+
if (content[i + 1] === '"') {
|
|
37
|
+
field += '"';
|
|
38
|
+
i += 1;
|
|
39
|
+
} else quoted = false;
|
|
40
|
+
} else field += ch;
|
|
41
|
+
continue;
|
|
42
|
+
}
|
|
43
|
+
if (ch === '"') quoted = true;
|
|
44
|
+
else if (ch === delimiter) {
|
|
45
|
+
row.push(field);
|
|
46
|
+
field = '';
|
|
47
|
+
} else if (ch === '\n') {
|
|
48
|
+
row.push(field);
|
|
49
|
+
field = '';
|
|
50
|
+
rows.push(row);
|
|
51
|
+
row = [];
|
|
52
|
+
} else if (ch !== '\r') field += ch;
|
|
53
|
+
}
|
|
54
|
+
if (field.length > 0 || row.length > 0) {
|
|
55
|
+
row.push(field);
|
|
56
|
+
rows.push(row);
|
|
57
|
+
}
|
|
58
|
+
return rows.filter((r) => r.some((c) => c.trim() !== ''));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
async function listFiles(target) {
|
|
62
|
+
const info = await stat(target);
|
|
63
|
+
if (info.isFile()) return [target];
|
|
64
|
+
const entries = await readdir(target, { withFileTypes: true });
|
|
65
|
+
const out = [];
|
|
66
|
+
for (const entry of entries.sort((a, b) => (a.name < b.name ? -1 : 1))) {
|
|
67
|
+
const full = path.join(target, entry.name);
|
|
68
|
+
if (entry.isDirectory()) out.push(...(await listFiles(full)));
|
|
69
|
+
else if (entry.isFile() && !entry.name.startsWith('.')) out.push(full);
|
|
70
|
+
}
|
|
71
|
+
return out;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function pickFields(obj, dataset) {
|
|
75
|
+
const prompt = obj[dataset.promptField];
|
|
76
|
+
const completion = obj[dataset.completionField];
|
|
77
|
+
const text = obj[dataset.textField];
|
|
78
|
+
if (prompt !== undefined && completion !== undefined) {
|
|
79
|
+
return { prompt: String(prompt), completion: String(completion) };
|
|
80
|
+
}
|
|
81
|
+
if (text !== undefined) return { prompt: null, completion: null, text: String(text) };
|
|
82
|
+
throw new Error(
|
|
83
|
+
`record is missing usable fields; expected "${dataset.promptField}"+"${dataset.completionField}" or "${dataset.textField}"`,
|
|
84
|
+
);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function makeRecord(dataset, fields, source) {
|
|
88
|
+
const text = fields.text ?? `${fields.prompt}${fields.completion}`;
|
|
89
|
+
return {
|
|
90
|
+
id: sha256(`${source.dataset}:${source.file}:${source.line}:${text}`).slice(0, 16),
|
|
91
|
+
prompt: fields.prompt ?? null,
|
|
92
|
+
completion: fields.completion ?? null,
|
|
93
|
+
text,
|
|
94
|
+
source,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function ingestDataset(descriptor, index = 0, { baseDir = process.cwd() } = {}) {
|
|
99
|
+
const dataset = normalizeDatasetDescriptor(descriptor, index);
|
|
100
|
+
const target = path.isAbsolute(dataset.path) ? dataset.path : path.join(baseDir, dataset.path);
|
|
101
|
+
let files;
|
|
102
|
+
try {
|
|
103
|
+
files = await listFiles(target);
|
|
104
|
+
} catch (err) {
|
|
105
|
+
throw new Error(`dataset "${dataset.name}" path is unreadable: ${err.message}`);
|
|
106
|
+
}
|
|
107
|
+
const records = [];
|
|
108
|
+
const errors = [];
|
|
109
|
+
for (const file of files) {
|
|
110
|
+
const content = await readFile(file, 'utf8');
|
|
111
|
+
const format = detectFormat(file, dataset.format);
|
|
112
|
+
const relative = path.relative(baseDir, file) || path.basename(file);
|
|
113
|
+
if (format === 'jsonl') {
|
|
114
|
+
const lines = content.split('\n');
|
|
115
|
+
for (let i = 0; i < lines.length; i += 1) {
|
|
116
|
+
const line = lines[i].trim();
|
|
117
|
+
if (!line) continue;
|
|
118
|
+
try {
|
|
119
|
+
const fields = pickFields(JSON.parse(line), dataset);
|
|
120
|
+
records.push(makeRecord(dataset, fields, sourceRecord(dataset, { file: relative, line: i + 1, rawSha256: sha256(line) })));
|
|
121
|
+
} catch (err) {
|
|
122
|
+
errors.push({ file: relative, line: i + 1, reason: err.message });
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
} else if (format === 'json') {
|
|
126
|
+
try {
|
|
127
|
+
const parsed = JSON.parse(content);
|
|
128
|
+
const items = Array.isArray(parsed) ? parsed : parsed.records ?? [];
|
|
129
|
+
items.forEach((item, i) => {
|
|
130
|
+
try {
|
|
131
|
+
const fields = pickFields(item, dataset);
|
|
132
|
+
const raw = JSON.stringify(item);
|
|
133
|
+
records.push(makeRecord(dataset, fields, sourceRecord(dataset, { file: relative, line: i + 1, rawSha256: sha256(raw) })));
|
|
134
|
+
} catch (err) {
|
|
135
|
+
errors.push({ file: relative, line: i + 1, reason: err.message });
|
|
136
|
+
}
|
|
137
|
+
});
|
|
138
|
+
} catch (err) {
|
|
139
|
+
errors.push({ file: relative, line: 0, reason: `invalid json: ${err.message}` });
|
|
140
|
+
}
|
|
141
|
+
} else if (format === 'csv') {
|
|
142
|
+
const delimiter = path.extname(file).toLowerCase() === '.tsv' ? '\t' : ',';
|
|
143
|
+
const rows = parseDelimited(content, delimiter);
|
|
144
|
+
if (rows.length === 0) continue;
|
|
145
|
+
const header = rows[0].map((h) => h.trim());
|
|
146
|
+
for (let i = 1; i < rows.length; i += 1) {
|
|
147
|
+
const obj = Object.fromEntries(header.map((h, c) => [h, rows[i][c] ?? '']));
|
|
148
|
+
try {
|
|
149
|
+
const fields = pickFields(obj, dataset);
|
|
150
|
+
records.push(makeRecord(dataset, fields, sourceRecord(dataset, { file: relative, line: i + 1, rawSha256: sha256(rows[i].join(delimiter)) })));
|
|
151
|
+
} catch (err) {
|
|
152
|
+
errors.push({ file: relative, line: i + 1, reason: err.message });
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
} else {
|
|
156
|
+
// Plain text: blank-line separated documents.
|
|
157
|
+
const chunks = content.split(/\n\s*\n/);
|
|
158
|
+
let line = 1;
|
|
159
|
+
for (const chunk of chunks) {
|
|
160
|
+
const value = chunk.trim();
|
|
161
|
+
const lineStart = line;
|
|
162
|
+
line += chunk.split('\n').length;
|
|
163
|
+
if (!value) continue;
|
|
164
|
+
records.push(makeRecord(dataset, { text: value }, sourceRecord(dataset, { file: relative, line: lineStart, rawSha256: sha256(value) })));
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
return { dataset, files: files.length, records, errors };
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
export async function ingestAll(descriptors, { baseDir = process.cwd() } = {}) {
|
|
172
|
+
if (!Array.isArray(descriptors) || descriptors.length === 0) {
|
|
173
|
+
throw new Error('at least one dataset descriptor is required');
|
|
174
|
+
}
|
|
175
|
+
const results = [];
|
|
176
|
+
for (let i = 0; i < descriptors.length; i += 1) {
|
|
177
|
+
results.push(await ingestDataset(descriptors[i], i, { baseDir }));
|
|
178
|
+
}
|
|
179
|
+
return {
|
|
180
|
+
records: results.flatMap((r) => r.records),
|
|
181
|
+
errors: results.flatMap((r) => r.errors),
|
|
182
|
+
datasets: results.map((r) => ({ name: r.dataset.name, files: r.files, records: r.records.length, errors: r.errors.length })),
|
|
183
|
+
};
|
|
184
|
+
}
|
package/src/data/pii.mjs
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// Sensitive-information detection and redaction.
|
|
2
|
+
//
|
|
3
|
+
// The foundry is pointed at private enterprise data, so every record passes
|
|
4
|
+
// through here before it can reach a training set. Detection is conservative
|
|
5
|
+
// (prefer a false positive over leaking a secret) and redaction is in-place so
|
|
6
|
+
// a usable record survives when only part of it is sensitive.
|
|
7
|
+
|
|
8
|
+
const LUHN_CANDIDATE = /\b(?:\d[ -]?){12,18}\d\b/g;
|
|
9
|
+
|
|
10
|
+
function luhnValid(digits) {
|
|
11
|
+
let sum = 0;
|
|
12
|
+
let double = false;
|
|
13
|
+
for (let i = digits.length - 1; i >= 0; i -= 1) {
|
|
14
|
+
let d = digits.charCodeAt(i) - 48;
|
|
15
|
+
if (double) {
|
|
16
|
+
d *= 2;
|
|
17
|
+
if (d > 9) d -= 9;
|
|
18
|
+
}
|
|
19
|
+
sum += d;
|
|
20
|
+
double = !double;
|
|
21
|
+
}
|
|
22
|
+
return digits.length >= 13 && sum % 10 === 0;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function cnIdChecksum(id) {
|
|
26
|
+
if (!/^\d{17}[\dXx]$/.test(id)) return false;
|
|
27
|
+
const weights = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
|
|
28
|
+
const checks = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
|
|
29
|
+
let sum = 0;
|
|
30
|
+
for (let i = 0; i < 17; i += 1) sum += (id.charCodeAt(i) - 48) * weights[i];
|
|
31
|
+
return checks[sum % 11] === id[17].toUpperCase();
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export const PII_RULES = [
|
|
35
|
+
{
|
|
36
|
+
kind: 'email',
|
|
37
|
+
severity: 'high',
|
|
38
|
+
placeholder: '[REDACTED:EMAIL]',
|
|
39
|
+
pattern: /\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b/g,
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
kind: 'credential',
|
|
43
|
+
severity: 'critical',
|
|
44
|
+
placeholder: '[REDACTED:CREDENTIAL]',
|
|
45
|
+
// Common secret shapes: provider keys plus generic assignments.
|
|
46
|
+
pattern: /\b(?:sk-[A-Za-z0-9]{16,}|ghp_[A-Za-z0-9]{20,}|AKIA[0-9A-Z]{12,}|xox[baprs]-[A-Za-z0-9-]{10,})\b/g,
|
|
47
|
+
},
|
|
48
|
+
{
|
|
49
|
+
kind: 'credential',
|
|
50
|
+
severity: 'critical',
|
|
51
|
+
placeholder: '$1=[REDACTED:CREDENTIAL]',
|
|
52
|
+
pattern: /\b(password|passwd|secret|api[_-]?key|access[_-]?token|private[_-]?key)\s*[=:]\s*["']?[^\s"',;]{6,}["']?/gi,
|
|
53
|
+
replace: (match, name) => `${name}=[REDACTED:CREDENTIAL]`,
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
kind: 'cn_id',
|
|
57
|
+
severity: 'critical',
|
|
58
|
+
placeholder: '[REDACTED:CN_ID]',
|
|
59
|
+
pattern: /\b\d{17}[\dXx]\b/g,
|
|
60
|
+
validate: (m) => cnIdChecksum(m),
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
kind: 'bank_card',
|
|
64
|
+
severity: 'critical',
|
|
65
|
+
placeholder: '[REDACTED:CARD]',
|
|
66
|
+
pattern: LUHN_CANDIDATE,
|
|
67
|
+
validate: (m) => luhnValid(m.replace(/[^\d]/g, '')),
|
|
68
|
+
},
|
|
69
|
+
{
|
|
70
|
+
kind: 'phone',
|
|
71
|
+
severity: 'high',
|
|
72
|
+
placeholder: '[REDACTED:PHONE]',
|
|
73
|
+
pattern: /(?:\+\d{1,3}[\s-]?)?\b1[3-9]\d{9}\b|\+\d{1,3}[\s-]?\d{3}[\s-]?\d{3}[\s-]?\d{4}\b/g,
|
|
74
|
+
},
|
|
75
|
+
{
|
|
76
|
+
kind: 'ip',
|
|
77
|
+
severity: 'medium',
|
|
78
|
+
placeholder: '[REDACTED:IP]',
|
|
79
|
+
pattern: /\b(?:(?:25[0-5]|2[0-4]\d|1?\d?\d)\.){3}(?:25[0-5]|2[0-4]\d|1?\d?\d)\b/g,
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
kind: 'private_key_block',
|
|
83
|
+
severity: 'critical',
|
|
84
|
+
placeholder: '[REDACTED:PRIVATE_KEY]',
|
|
85
|
+
pattern: /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g,
|
|
86
|
+
},
|
|
87
|
+
];
|
|
88
|
+
|
|
89
|
+
export const SEVERITY_ORDER = { low: 0, medium: 1, high: 2, critical: 3 };
|
|
90
|
+
|
|
91
|
+
export function scanPii(text) {
|
|
92
|
+
const findings = [];
|
|
93
|
+
const value = String(text ?? '');
|
|
94
|
+
for (const rule of PII_RULES) {
|
|
95
|
+
rule.pattern.lastIndex = 0;
|
|
96
|
+
let match;
|
|
97
|
+
while ((match = rule.pattern.exec(value)) !== null) {
|
|
98
|
+
if (match[0].length === 0) {
|
|
99
|
+
rule.pattern.lastIndex += 1;
|
|
100
|
+
continue;
|
|
101
|
+
}
|
|
102
|
+
if (rule.validate && !rule.validate(match[0])) continue;
|
|
103
|
+
findings.push({ kind: rule.kind, severity: rule.severity, start: match.index, length: match[0].length });
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
findings.sort((a, b) => a.start - b.start || b.length - a.length);
|
|
107
|
+
return findings;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export function redactPii(text) {
|
|
111
|
+
let value = String(text ?? '');
|
|
112
|
+
const applied = [];
|
|
113
|
+
for (const rule of PII_RULES) {
|
|
114
|
+
rule.pattern.lastIndex = 0;
|
|
115
|
+
value = value.replace(rule.pattern, (...args) => {
|
|
116
|
+
const match = args[0];
|
|
117
|
+
if (rule.validate && !rule.validate(match)) return match;
|
|
118
|
+
applied.push({ kind: rule.kind, severity: rule.severity });
|
|
119
|
+
return rule.replace ? rule.replace(...args) : rule.placeholder;
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
return { text: value, applied };
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function highestSeverity(findings) {
|
|
126
|
+
return findings.reduce((worst, f) => (SEVERITY_ORDER[f.severity] > SEVERITY_ORDER[worst ?? 'low'] ? f.severity : worst), null);
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
// Policy hook used by the pipeline: `redact` keeps the record with secrets
|
|
130
|
+
// removed, `drop` discards it, `fail` aborts the whole job.
|
|
131
|
+
export function applyPiiPolicy(text, { policy = 'redact', blockSeverity = 'critical' } = {}) {
|
|
132
|
+
const findings = scanPii(text);
|
|
133
|
+
if (findings.length === 0) return { action: 'keep', text: String(text ?? ''), findings };
|
|
134
|
+
const worst = highestSeverity(findings);
|
|
135
|
+
if (policy === 'fail' && SEVERITY_ORDER[worst] >= SEVERITY_ORDER[blockSeverity]) {
|
|
136
|
+
const kinds = [...new Set(findings.map((f) => f.kind))].join(', ');
|
|
137
|
+
throw new Error(`pii policy "fail": ${worst} sensitive data detected (${kinds})`);
|
|
138
|
+
}
|
|
139
|
+
if (policy === 'drop') return { action: 'drop', text: String(text ?? ''), findings, worst };
|
|
140
|
+
const { text: redacted, applied } = redactPii(text);
|
|
141
|
+
return { action: 'redact', text: redacted, findings, worst, applied };
|
|
142
|
+
}
|