@takeokunn/gbrainx 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 +38 -2
- package/dist/core.mjs +1346 -0
- package/dist/gbrainx.mjs +7097 -0
- package/dist/web/client/assets/api-BvRk9kiK.js +0 -0
- package/dist/web/client/assets/demo-G0WCPBHC.js +10 -0
- package/dist/web/client/assets/entry.client-BMJZABtH.js +9 -0
- package/dist/web/client/assets/gbrainx-DfnQgPxe.js +49 -0
- package/dist/web/client/assets/health-BvRk9kiK.js +0 -0
- package/dist/web/client/assets/home-DmjYPYzC.js +7 -0
- package/dist/web/client/assets/i18n-CbBRRmtS.js +1 -0
- package/dist/web/client/assets/jsx-runtime-C8YK_IxR.js +16 -0
- package/dist/web/client/assets/lib-C32AnKSP.js +1 -0
- package/dist/web/client/assets/manifest-24d3a028.js +1 -0
- package/dist/web/client/assets/root-C-cLqVHP.js +1 -0
- package/dist/web/client/assets/root-D4kqIC2S.css +2 -0
- package/dist/web/client/assets/root-i18n-_0Yddpt_.js +1 -0
- package/dist/web/client/assets/sell-C3y92_D_.js +1 -0
- package/dist/web/client/assets/sell-ChG4r-W3.css +1 -0
- package/dist/web/client/assets/use-lp-language-ij45BzB4.js +1 -0
- package/dist/web/client/avatars/aiko.svg +7 -0
- package/dist/web/client/avatars/daniel.svg +7 -0
- package/dist/web/client/avatars/ken.svg +7 -0
- package/dist/web/client/avatars/leo.svg +7 -0
- package/dist/web/client/avatars/yui.svg +7 -0
- package/dist/web/client/demo.mp4 +0 -0
- package/dist/web/client/favicon.ico +0 -0
- package/dist/web/server/assets/cloudflare-context-CIZdXilT.js +3426 -0
- package/dist/web/server/assets/rolldown-runtime-nwr4M8im.js +34 -0
- package/dist/web/server/assets/server-build-DGFJ8-cb.js +22842 -0
- package/dist/web/server/assets/server-build-DarI7Ueq.css +2 -0
- package/package.json +9 -4
package/dist/core.mjs
ADDED
|
@@ -0,0 +1,1346 @@
|
|
|
1
|
+
// ../core/src/scrub.ts
|
|
2
|
+
var patterns = [
|
|
3
|
+
{
|
|
4
|
+
kind: "STRIPE_KEY",
|
|
5
|
+
pattern: /\bsk_(?:live|test)_[0-9A-Za-z]{8,}/g
|
|
6
|
+
},
|
|
7
|
+
{
|
|
8
|
+
kind: "API_KEY",
|
|
9
|
+
pattern: /\bsk-[0-9A-Za-z_-]{16,}/g
|
|
10
|
+
},
|
|
11
|
+
{
|
|
12
|
+
kind: "AWS_KEY",
|
|
13
|
+
pattern: /AKIA[0-9A-Z]{16}/g
|
|
14
|
+
},
|
|
15
|
+
{
|
|
16
|
+
kind: "GITHUB_TOKEN",
|
|
17
|
+
pattern: /\bgh[pousr]_[0-9A-Za-z]{20,}/g
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
kind: "JWT",
|
|
21
|
+
pattern: /(?<![\w-])eyJ[\w-]+\.[\w-]+\.[\w-]+/g
|
|
22
|
+
},
|
|
23
|
+
{
|
|
24
|
+
kind: "CONNECTION",
|
|
25
|
+
pattern: /\b[a-zA-Z][a-zA-Z0-9+.-]{0,31}:\/\/[^\s/@]+@/g
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
kind: "QUERY_TOKEN",
|
|
29
|
+
pattern: /[?&](?:access_token|token|api_key|apikey|key|secret|password)=([^&#\s]+)/gi,
|
|
30
|
+
group: 1
|
|
31
|
+
},
|
|
32
|
+
{
|
|
33
|
+
kind: "ENV",
|
|
34
|
+
pattern: /^[ \t]*(?:export[ \t]+)?[A-Za-z_][A-Za-z0-9_]{0,127}[ \t]*=[ \t]*("[^\r\n]*|'[^\r\n]*|[^\s#]+)/gm,
|
|
35
|
+
group: 1
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
kind: "EMAIL",
|
|
39
|
+
pattern: /[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63}){1,8}/g
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
kind: "HOST",
|
|
43
|
+
pattern: /[\w.-]{1,253}\.(?:local|internal|corp)\b/gi
|
|
44
|
+
},
|
|
45
|
+
{
|
|
46
|
+
kind: "IP",
|
|
47
|
+
pattern: /\b(?:\d{1,3}\.){3}\d{1,3}\b/g
|
|
48
|
+
}
|
|
49
|
+
];
|
|
50
|
+
function entropy(value) {
|
|
51
|
+
const counts = /* @__PURE__ */ new Map();
|
|
52
|
+
for (const char of value) counts.set(char, (counts.get(char) ?? 0) + 1);
|
|
53
|
+
let result = 0;
|
|
54
|
+
for (const count of counts.values()) {
|
|
55
|
+
const p = count / value.length;
|
|
56
|
+
result -= p * Math.log2(p);
|
|
57
|
+
}
|
|
58
|
+
return result;
|
|
59
|
+
}
|
|
60
|
+
var homePath = /(?:\/(?:Users|home)\/[^/\s\\]+(?:\/|\\)|\b[A-Za-z]:\\Users\\[^/\s\\]+\\)/gi;
|
|
61
|
+
var gbrainPath = /~[\\/]\.gbrain(?:[\\/](?:\\[ \t]|[^\s\]})"'<>,;])*)?(?=$|[\s\]})"'<>,;])/gi;
|
|
62
|
+
function scrubSourceMetadata(input, replace) {
|
|
63
|
+
const lines = input.split(/(?<=\n)|(?<=\r)(?!\n)/);
|
|
64
|
+
let start = -1;
|
|
65
|
+
let fence = "";
|
|
66
|
+
for (let i = 0; i < lines.length; i++) {
|
|
67
|
+
const line = lines[i];
|
|
68
|
+
const marker = /^ {0,3}(`{3,}|~{3,})/.exec(line)?.[1];
|
|
69
|
+
if (marker) {
|
|
70
|
+
if (!fence) fence = marker;
|
|
71
|
+
else if (marker[0] === fence[0] && marker.length >= fence.length) fence = "";
|
|
72
|
+
continue;
|
|
73
|
+
}
|
|
74
|
+
if (fence || !/^\uFEFF?(?:---|\.\.\.)[ \t]*(?:#.*)?(?:\r\n|\n|\r)?$/.test(line)) continue;
|
|
75
|
+
if (start < 0) {
|
|
76
|
+
if (line.replace(/^\uFEFF/, "").startsWith("---")) start = i;
|
|
77
|
+
continue;
|
|
78
|
+
}
|
|
79
|
+
for (let j = start + 1; j < i; j++) {
|
|
80
|
+
const explicit = /^[ \t]*(?:-[ \t]+)?\?[ \t]+["']?(raw_source|source_path|source_file|source_uri|source_url|import_source|transcript_source|original_source|origin|source)["']?[ \t]*(?:\r\n|\n|\r)$/i.exec(lines[j]);
|
|
81
|
+
if (explicit && j + 1 < i) {
|
|
82
|
+
const item = /^([ \t]*:[ \t]*)([^\r\n]*)(\r\n|\n|\r|$)/.exec(lines[j + 1]);
|
|
83
|
+
if (item) {
|
|
84
|
+
let value = item[2];
|
|
85
|
+
let end = j + 2;
|
|
86
|
+
const indent = /^[ \t]*/.exec(lines[j + 1])[0].length;
|
|
87
|
+
while (end < i && (!lines[end].trim() || /^[ \t]+\S/.test(lines[end]) && /^[ \t]*/.exec(lines[end])[0].length > indent)) {
|
|
88
|
+
value += item[3] + lines[end].replace(/(?:\r\n|\n|\r)$/, "");
|
|
89
|
+
lines[end++] = "";
|
|
90
|
+
}
|
|
91
|
+
const purchased = explicit[1].toLowerCase() === "source" && /^(?:gbrainx|"gbrainx"|'gbrainx')\s*(?:#.*)?$/i.test(item[2]);
|
|
92
|
+
if (!purchased || value !== item[2]) replace(value);
|
|
93
|
+
lines[j] = purchased ? `source: gbrainx${item[3]}` : "";
|
|
94
|
+
lines[j + 1] = "";
|
|
95
|
+
j = end - 1;
|
|
96
|
+
continue;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (/[{,][ \t]*["']?(?:raw_source|source_path|source_file|source_uri|source_url|import_source|transcript_source|original_source|origin|source)["']?[ \t]*:/i.test(lines[j]) || /[{,][ \t]*"[^"\r\n]*\\/.test(lines[j])) {
|
|
100
|
+
const value = lines[j].replace(/(?:\r\n|\n|\r)$/, "");
|
|
101
|
+
const newline = lines[j].slice(value.length);
|
|
102
|
+
const purchase = /[{,][ \t]*["']?source["']?[ \t]*:[ \t]*(?:gbrainx|"gbrainx"|'gbrainx')[ \t]*(?=[,}])/i.test(value);
|
|
103
|
+
const indent = /^[ \t]*/.exec(value)[0];
|
|
104
|
+
replace(value);
|
|
105
|
+
lines[j] = purchase ? `${indent}source: gbrainx${newline}` : "";
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
const match = /^([ \t]*(?:-[ \t]+)*("(?:[^"\\]|\\.)*"|'[^']*'|[A-Za-z_][A-Za-z0-9_-]*)[ \t]*:[ \t]*)([^\r\n]*)(\r\n|\n|\r|$)/.exec(lines[j]);
|
|
109
|
+
const baseIndent = /^[ \t]*/.exec(lines[j])[0].length;
|
|
110
|
+
const nextIsContinuation = j + 1 < i && /^[ \t]+\S/.test(lines[j + 1]) && !/^[ \t]+["']?[A-Za-z_][A-Za-z0-9_-]*["']?[ \t]*:/.test(lines[j + 1]);
|
|
111
|
+
if (!match) continue;
|
|
112
|
+
const rawKey = match[2].replace(/^["']|["']$/g, "");
|
|
113
|
+
const key = rawKey.replace(/\\x([0-9a-f]{2})|\\u([0-9a-f]{4})/gi, (_, x, u) => String.fromCharCode(parseInt(x ?? u, 16))).toLowerCase();
|
|
114
|
+
if (!/^(?:raw_source|source_path|source_file|source_uri|source_url|import_source|transcript_source|original_source|origin|source)$/.test(key) && !rawKey.includes("\\")) continue;
|
|
115
|
+
if (key === "source" && /^(?:gbrainx|"gbrainx"|'gbrainx')\s*(?:#.*)?$/i.test(match[3])) {
|
|
116
|
+
if (nextIsContinuation) {
|
|
117
|
+
const parts = [];
|
|
118
|
+
let end = j + 1;
|
|
119
|
+
while (end < i && /^[ \t]+\S/.test(lines[end]) && !/^[ \t]+["']?[A-Za-z_][A-Za-z0-9_-]*["']?[ \t]*:/.test(lines[end])) {
|
|
120
|
+
parts.push(lines[end].replace(/(?:\r\n|\n|\r)$/, ""));
|
|
121
|
+
lines[end++] = "";
|
|
122
|
+
}
|
|
123
|
+
replace(parts.join(match[4]));
|
|
124
|
+
j = end - 1;
|
|
125
|
+
}
|
|
126
|
+
continue;
|
|
127
|
+
}
|
|
128
|
+
let value = match[3];
|
|
129
|
+
let end = j + 1;
|
|
130
|
+
const quote = value[0] === "\"" || value[0] === "'" ? value[0] : "";
|
|
131
|
+
const hasClosingQuote = (text, offset) => {
|
|
132
|
+
for (let k = offset; k < text.length; k++) {
|
|
133
|
+
if (quote === "\"" && text[k] === "\\") {
|
|
134
|
+
k++;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
if (text[k] !== quote) continue;
|
|
138
|
+
if (quote === "'" && text[k + 1] === "'") {
|
|
139
|
+
k++;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
return true;
|
|
143
|
+
}
|
|
144
|
+
return false;
|
|
145
|
+
};
|
|
146
|
+
if (quote && !hasClosingQuote(value, 1)) while (end < i) {
|
|
147
|
+
const next = lines[end].replace(/(?:\r\n|\n|\r)$/, "");
|
|
148
|
+
value += match[4] + next;
|
|
149
|
+
lines[end++] = "";
|
|
150
|
+
if (hasClosingQuote(next, 0)) break;
|
|
151
|
+
}
|
|
152
|
+
else if (!quote) while (end < i && (!lines[end].trim() || /^[ \t]+\S/.test(lines[end]) && /^[ \t]*/.exec(lines[end])[0].length > baseIndent)) {
|
|
153
|
+
value += match[4] + lines[end].replace(/(?:\r\n|\n|\r)$/, "");
|
|
154
|
+
lines[end++] = "";
|
|
155
|
+
}
|
|
156
|
+
replace(value);
|
|
157
|
+
lines[j] = "";
|
|
158
|
+
j = end - 1;
|
|
159
|
+
}
|
|
160
|
+
start = -1;
|
|
161
|
+
}
|
|
162
|
+
return lines.join("");
|
|
163
|
+
}
|
|
164
|
+
function wordSlug(value) {
|
|
165
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)+$/.test(value)) return false;
|
|
166
|
+
return value.split("-").filter((part) => /^[a-z]{3,}$/.test(part)).length >= 2;
|
|
167
|
+
}
|
|
168
|
+
function pathComponent(value) {
|
|
169
|
+
if (/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.test(value)) return true;
|
|
170
|
+
const uuidSuffix = /^(.*)-[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i.exec(value);
|
|
171
|
+
if (uuidSuffix) value = uuidSuffix[1];
|
|
172
|
+
if (wordSlug(value)) return true;
|
|
173
|
+
if (!/^(?:[a-z0-9]+(?:[-_][a-z0-9]+)*|[A-Z][a-z]+)$/.test(value)) return false;
|
|
174
|
+
return value.split(/[-_]/).every((part) => {
|
|
175
|
+
const transitions = part.match(/(?<=[a-z])(?=[0-9])|(?<=[0-9])(?=[a-z])/g);
|
|
176
|
+
return !(part.length >= 20 && /[a-z]/.test(part) && /[0-9]/.test(part) && entropy(part) >= 4) && (transitions?.length ?? 0) <= 2 && !/^[a-f0-9]{20,}$/.test(part);
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
function entropySecret(value) {
|
|
180
|
+
if (/^sk-[A-Za-z0-9_-]{16,}$/.test(value)) return true;
|
|
181
|
+
if (/^[a-f0-9]{20,}$/i.test(value) && /[a-f]/i.test(value) && /[0-9]/.test(value)) return entropy(value.toLowerCase()) >= 3.2;
|
|
182
|
+
if (value.startsWith("REDACTED_") || entropy(value) < 4) return false;
|
|
183
|
+
if (value.includes("-") && pathComponent(value)) return false;
|
|
184
|
+
if (value.includes("/")) {
|
|
185
|
+
const parts = value.split("/").filter(Boolean);
|
|
186
|
+
if (parts.length > 1 && parts.every(pathComponent)) return false;
|
|
187
|
+
}
|
|
188
|
+
return true;
|
|
189
|
+
}
|
|
190
|
+
function replaceTerm(text, term, replace) {
|
|
191
|
+
const bounded = /^[A-Za-z0-9]+$/.test(term);
|
|
192
|
+
let cursor = 0;
|
|
193
|
+
let search = 0;
|
|
194
|
+
const parts = [];
|
|
195
|
+
while (true) {
|
|
196
|
+
const index = text.indexOf(term, search);
|
|
197
|
+
if (index < 0) break;
|
|
198
|
+
const end = index + term.length;
|
|
199
|
+
if (bounded && (/[A-Za-z0-9]/.test(text[index - 1] ?? "") || /[A-Za-z0-9]/.test(text[end] ?? ""))) {
|
|
200
|
+
search = index + 1;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
parts.push(text.slice(cursor, index), replace());
|
|
204
|
+
cursor = end;
|
|
205
|
+
search = end;
|
|
206
|
+
}
|
|
207
|
+
parts.push(text.slice(cursor));
|
|
208
|
+
return parts.join("");
|
|
209
|
+
}
|
|
210
|
+
function buildForbiddenDictionary(excluded, retained) {
|
|
211
|
+
const terms = /* @__PURE__ */ new Set();
|
|
212
|
+
for (const page of excluded) for (const term of [
|
|
213
|
+
page.title,
|
|
214
|
+
page.id,
|
|
215
|
+
...page.markdown.match(/\b[A-Z][a-zA-Z]{2,}\b/g) ?? []
|
|
216
|
+
]) if (term.trim()) terms.add(term.trim());
|
|
217
|
+
const all = [...terms].sort((a, b) => b.length - a.length || a.localeCompare(b));
|
|
218
|
+
return {
|
|
219
|
+
terms: all,
|
|
220
|
+
shared: all.filter((term) => retained.some((text) => text.includes(term)))
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
function scrubDetailed(input, dictionary = {
|
|
224
|
+
terms: [],
|
|
225
|
+
shared: []
|
|
226
|
+
}) {
|
|
227
|
+
let markdown = input;
|
|
228
|
+
const changes = [];
|
|
229
|
+
const replacements = /* @__PURE__ */ new Map();
|
|
230
|
+
const counts = /* @__PURE__ */ new Map();
|
|
231
|
+
const record = (kind, value) => {
|
|
232
|
+
const key = `${kind}\0${value}`;
|
|
233
|
+
let replacement = replacements.get(key);
|
|
234
|
+
if (!replacement) {
|
|
235
|
+
const number = (counts.get(kind) ?? 0) + 1;
|
|
236
|
+
counts.set(kind, number);
|
|
237
|
+
replacement = `[REDACTED_${kind}_${number}]`;
|
|
238
|
+
replacements.set(key, replacement);
|
|
239
|
+
}
|
|
240
|
+
changes.push({
|
|
241
|
+
kind,
|
|
242
|
+
before: value,
|
|
243
|
+
after: replacement
|
|
244
|
+
});
|
|
245
|
+
return replacement;
|
|
246
|
+
};
|
|
247
|
+
const begin = "-----BEGIN ";
|
|
248
|
+
let cursor = 0;
|
|
249
|
+
let copied = 0;
|
|
250
|
+
const pemParts = [];
|
|
251
|
+
while (true) {
|
|
252
|
+
const start = markdown.indexOf(begin, cursor);
|
|
253
|
+
if (start < 0) break;
|
|
254
|
+
const lineEnd = markdown.indexOf("\n", start);
|
|
255
|
+
if (lineEnd < 0) break;
|
|
256
|
+
const header = markdown.slice(start, lineEnd).trimEnd();
|
|
257
|
+
const match = /^-----BEGIN ([A-Z ]{0,32}PRIVATE KEY)-----$/.exec(header);
|
|
258
|
+
if (!match) {
|
|
259
|
+
cursor = lineEnd + 1;
|
|
260
|
+
continue;
|
|
261
|
+
}
|
|
262
|
+
const endMarker = `-----END ${match[1]}-----`;
|
|
263
|
+
const end = markdown.indexOf(endMarker, lineEnd);
|
|
264
|
+
if (end < 0) break;
|
|
265
|
+
const stop = end + endMarker.length;
|
|
266
|
+
pemParts.push(markdown.slice(copied, start), record("PRIVATE_KEY", markdown.slice(start, stop)));
|
|
267
|
+
cursor = stop;
|
|
268
|
+
copied = stop;
|
|
269
|
+
}
|
|
270
|
+
pemParts.push(markdown.slice(copied));
|
|
271
|
+
markdown = pemParts.join("");
|
|
272
|
+
markdown = markdown.replace(homePath, (value) => {
|
|
273
|
+
changes.push({
|
|
274
|
+
kind: "HOME_PATH",
|
|
275
|
+
before: value,
|
|
276
|
+
after: "~/"
|
|
277
|
+
});
|
|
278
|
+
return "~/";
|
|
279
|
+
});
|
|
280
|
+
markdown = markdown.replace(gbrainPath, (value) => record("GBRAIN_PATH", value));
|
|
281
|
+
markdown = scrubSourceMetadata(markdown, (value) => record("SOURCE", value));
|
|
282
|
+
for (const { kind, pattern, group } of patterns) markdown = markdown.replace(pattern, (...args) => {
|
|
283
|
+
const whole = args[0];
|
|
284
|
+
const value = group ? args[group] : whole;
|
|
285
|
+
if (/^\[REDACTED_[A-Z_]+_\d+\]$/.test(value)) return whole;
|
|
286
|
+
const replacement = record(kind, value);
|
|
287
|
+
return group ? whole.slice(0, whole.lastIndexOf(value)) + replacement : replacement;
|
|
288
|
+
});
|
|
289
|
+
markdown = markdown.replace(/[A-Za-z0-9+/_=-]{20,}/g, (value) => {
|
|
290
|
+
if (!entropySecret(value)) return value;
|
|
291
|
+
return record("ENTROPY", value);
|
|
292
|
+
});
|
|
293
|
+
for (const term of dictionary.terms) {
|
|
294
|
+
if (!term || !markdown.includes(term)) continue;
|
|
295
|
+
markdown = markdown.split(/(\[REDACTED_[A-Z_]+_\d+\])/g).map((part) => {
|
|
296
|
+
if (/^\[REDACTED_[A-Z_]+_\d+\]$/.test(part)) return part;
|
|
297
|
+
return replaceTerm(part, term, () => record("NAME", term));
|
|
298
|
+
}).join("");
|
|
299
|
+
}
|
|
300
|
+
const scrubbed = [...new Set(changes.map((change) => change.kind))].map((kind) => ({
|
|
301
|
+
kind,
|
|
302
|
+
count: changes.filter((change) => change.kind === kind).length
|
|
303
|
+
}));
|
|
304
|
+
return {
|
|
305
|
+
markdown,
|
|
306
|
+
scrubbed,
|
|
307
|
+
changes,
|
|
308
|
+
remaining: scanWithoutRescan(markdown, dictionary)
|
|
309
|
+
};
|
|
310
|
+
}
|
|
311
|
+
function scanWithoutRescan(markdown, dictionary) {
|
|
312
|
+
let count = 0;
|
|
313
|
+
count += [...markdown.matchAll(homePath)].length;
|
|
314
|
+
count += [...markdown.matchAll(gbrainPath)].length;
|
|
315
|
+
scrubSourceMetadata(markdown, () => {
|
|
316
|
+
count++;
|
|
317
|
+
return "";
|
|
318
|
+
});
|
|
319
|
+
if (/-----BEGIN [A-Z ]{0,32}PRIVATE KEY-----/.test(markdown)) count++;
|
|
320
|
+
for (const { pattern, group } of patterns) for (const match of markdown.matchAll(pattern)) if (!/^\[REDACTED_[A-Z_]+_\d+\]$/.test(group ? match[group] : match[0])) count++;
|
|
321
|
+
for (const match of markdown.matchAll(/[A-Za-z0-9+/_=-]{20,}/g)) if (entropySecret(match[0])) count++;
|
|
322
|
+
const parts = markdown.split(/\[REDACTED_[A-Z_]+_\d+\]/g);
|
|
323
|
+
for (const term of dictionary.terms) {
|
|
324
|
+
if (!term) continue;
|
|
325
|
+
let found = false;
|
|
326
|
+
for (const part of parts) {
|
|
327
|
+
if (!part.includes(term)) continue;
|
|
328
|
+
replaceTerm(part, term, () => {
|
|
329
|
+
found = true;
|
|
330
|
+
return "";
|
|
331
|
+
});
|
|
332
|
+
if (found) break;
|
|
333
|
+
}
|
|
334
|
+
if (found) count++;
|
|
335
|
+
}
|
|
336
|
+
return count;
|
|
337
|
+
}
|
|
338
|
+
function rescan(markdown, dictionary) {
|
|
339
|
+
return scanWithoutRescan(markdown, dictionary ?? {
|
|
340
|
+
terms: [],
|
|
341
|
+
shared: []
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
// ../core/src/money.ts
|
|
345
|
+
function isMoney(value) {
|
|
346
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && Number.isSafeInteger(Math.round(value * 100)) && Math.round(value * 100) / 100 === value;
|
|
347
|
+
}
|
|
348
|
+
// ../core/src/commerce.ts
|
|
349
|
+
function sessionFor(store, id, at) {
|
|
350
|
+
return store.sessions.find((session) => session.id === id) ?? {
|
|
351
|
+
id,
|
|
352
|
+
startedAt: at,
|
|
353
|
+
spentUsd: 0,
|
|
354
|
+
calls: []
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
function putSession(store, session) {
|
|
358
|
+
const index = store.sessions.findIndex((item) => item.id === session.id);
|
|
359
|
+
return index < 0 ? [...store.sessions, session] : store.sessions.map((item, i) => i === index ? session : item);
|
|
360
|
+
}
|
|
361
|
+
function recordSearch(store, sessionId, query, at) {
|
|
362
|
+
const session = sessionFor(store, sessionId, at);
|
|
363
|
+
const updated = {
|
|
364
|
+
...session,
|
|
365
|
+
calls: [...session.calls, {
|
|
366
|
+
tool: "search",
|
|
367
|
+
at,
|
|
368
|
+
summary: query
|
|
369
|
+
}]
|
|
370
|
+
};
|
|
371
|
+
return {
|
|
372
|
+
...store,
|
|
373
|
+
rev: store.rev + 1,
|
|
374
|
+
sessions: putSession(store, updated)
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
function hasPurchased(store, packId) {
|
|
378
|
+
return store.ledger.some((tx) => tx.packId === packId);
|
|
379
|
+
}
|
|
380
|
+
function decideBuy(store, packId, sessionId, score) {
|
|
381
|
+
const pack = store.packs.find((item) => item.id === packId);
|
|
382
|
+
if (!pack) return {
|
|
383
|
+
ok: false,
|
|
384
|
+
code: "pack_not_found"
|
|
385
|
+
};
|
|
386
|
+
if (hasPurchased(store, packId)) return { ok: true };
|
|
387
|
+
const spent = store.sessions.find((item) => item.id === sessionId)?.spentUsd ?? 0;
|
|
388
|
+
if (![
|
|
389
|
+
pack.priceUsd,
|
|
390
|
+
store.wallet.buyerUsd,
|
|
391
|
+
store.wallet.perPurchaseCapUsd,
|
|
392
|
+
store.wallet.sessionCapUsd,
|
|
393
|
+
spent
|
|
394
|
+
].every(isMoney)) return {
|
|
395
|
+
ok: false,
|
|
396
|
+
code: "invalid_amount"
|
|
397
|
+
};
|
|
398
|
+
const price = Math.round(pack.priceUsd * 100);
|
|
399
|
+
if (price > Math.round(store.wallet.buyerUsd * 100)) return {
|
|
400
|
+
ok: false,
|
|
401
|
+
code: "insufficient_balance",
|
|
402
|
+
needsApproval: true
|
|
403
|
+
};
|
|
404
|
+
if (price > Math.round(store.wallet.perPurchaseCapUsd * 100)) return {
|
|
405
|
+
ok: false,
|
|
406
|
+
code: "over_purchase_cap",
|
|
407
|
+
needsApproval: true
|
|
408
|
+
};
|
|
409
|
+
if (price + Math.round(spent * 100) > Math.round(store.wallet.sessionCapUsd * 100)) return {
|
|
410
|
+
ok: false,
|
|
411
|
+
code: "over_session_cap",
|
|
412
|
+
needsApproval: true
|
|
413
|
+
};
|
|
414
|
+
if (!Number.isFinite(score) || score < .5 || score > 1) return {
|
|
415
|
+
ok: false,
|
|
416
|
+
code: "low_score",
|
|
417
|
+
needsApproval: true
|
|
418
|
+
};
|
|
419
|
+
return { ok: true };
|
|
420
|
+
}
|
|
421
|
+
function buy(store, packId, sessionId, via, at, txId, expectedRev, score) {
|
|
422
|
+
const existing = store.ledger.find((tx) => tx.packId === packId);
|
|
423
|
+
if (existing) return {
|
|
424
|
+
ok: true,
|
|
425
|
+
store,
|
|
426
|
+
tx: existing,
|
|
427
|
+
rev: store.rev,
|
|
428
|
+
alreadyPurchased: true
|
|
429
|
+
};
|
|
430
|
+
if (store.rev !== expectedRev) return {
|
|
431
|
+
ok: false,
|
|
432
|
+
code: "revision_conflict"
|
|
433
|
+
};
|
|
434
|
+
const decision = decideBuy(store, packId, sessionId, score);
|
|
435
|
+
if (!decision.ok) return decision;
|
|
436
|
+
if (store.ledger.some((tx) => tx.id === txId)) return {
|
|
437
|
+
ok: false,
|
|
438
|
+
code: "duplicate_tx_id"
|
|
439
|
+
};
|
|
440
|
+
const pack = store.packs.find((item) => item.id === packId);
|
|
441
|
+
const session = sessionFor(store, sessionId, at);
|
|
442
|
+
const price = Math.round(pack.priceUsd * 100);
|
|
443
|
+
const author = Math.round(price * .9);
|
|
444
|
+
const tx = {
|
|
445
|
+
id: txId,
|
|
446
|
+
packId,
|
|
447
|
+
sessionId,
|
|
448
|
+
at,
|
|
449
|
+
amountUsd: price / 100,
|
|
450
|
+
authorUsd: author / 100,
|
|
451
|
+
feeUsd: (price - author) / 100,
|
|
452
|
+
via,
|
|
453
|
+
result: "running",
|
|
454
|
+
pagesUsed: []
|
|
455
|
+
};
|
|
456
|
+
const updated = {
|
|
457
|
+
...session,
|
|
458
|
+
spentUsd: (Math.round(session.spentUsd * 100) + price) / 100,
|
|
459
|
+
calls: [...session.calls, {
|
|
460
|
+
tool: "buy",
|
|
461
|
+
at,
|
|
462
|
+
summary: packId,
|
|
463
|
+
txId
|
|
464
|
+
}]
|
|
465
|
+
};
|
|
466
|
+
const next = {
|
|
467
|
+
...store,
|
|
468
|
+
rev: store.rev + 1,
|
|
469
|
+
wallet: {
|
|
470
|
+
...store.wallet,
|
|
471
|
+
buyerUsd: (Math.round(store.wallet.buyerUsd * 100) - price) / 100
|
|
472
|
+
},
|
|
473
|
+
ledger: [...store.ledger, tx],
|
|
474
|
+
sessions: putSession(store, updated)
|
|
475
|
+
};
|
|
476
|
+
return {
|
|
477
|
+
ok: true,
|
|
478
|
+
store: next,
|
|
479
|
+
tx,
|
|
480
|
+
rev: next.rev,
|
|
481
|
+
alreadyPurchased: false
|
|
482
|
+
};
|
|
483
|
+
}
|
|
484
|
+
function load(store, packId, page) {
|
|
485
|
+
const pack = store.packs.find((item) => item.id === packId);
|
|
486
|
+
if (!pack) return {
|
|
487
|
+
ok: false,
|
|
488
|
+
code: "pack_not_found"
|
|
489
|
+
};
|
|
490
|
+
if (!hasPurchased(store, packId)) return {
|
|
491
|
+
ok: false,
|
|
492
|
+
code: "not_purchased"
|
|
493
|
+
};
|
|
494
|
+
if (page === void 0) return {
|
|
495
|
+
ok: true,
|
|
496
|
+
content: pack.summary,
|
|
497
|
+
pages: pack.pages.map((item) => item.id)
|
|
498
|
+
};
|
|
499
|
+
const found = pack.pages.find((item) => item.id === page);
|
|
500
|
+
if (!found) return {
|
|
501
|
+
ok: false,
|
|
502
|
+
code: "page_not_found"
|
|
503
|
+
};
|
|
504
|
+
return {
|
|
505
|
+
ok: true,
|
|
506
|
+
content: found.markdown,
|
|
507
|
+
page: found.id
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
function setTxResult(store, txId, result, pagesUsed = []) {
|
|
511
|
+
const current = store.ledger.find((tx) => tx.id === txId);
|
|
512
|
+
if (!current) return {
|
|
513
|
+
ok: false,
|
|
514
|
+
code: "tx_not_found"
|
|
515
|
+
};
|
|
516
|
+
const tx = {
|
|
517
|
+
...current,
|
|
518
|
+
result,
|
|
519
|
+
pagesUsed: [...pagesUsed]
|
|
520
|
+
};
|
|
521
|
+
return {
|
|
522
|
+
ok: true,
|
|
523
|
+
store: {
|
|
524
|
+
...store,
|
|
525
|
+
rev: store.rev + 1,
|
|
526
|
+
ledger: store.ledger.map((item) => item.id === txId ? tx : item)
|
|
527
|
+
},
|
|
528
|
+
tx
|
|
529
|
+
};
|
|
530
|
+
}
|
|
531
|
+
function earnings(store) {
|
|
532
|
+
const packs = new Map(store.packs.filter((pack) => pack.author === "you").map((pack) => [pack.id, {
|
|
533
|
+
packId: pack.id,
|
|
534
|
+
uses: 0,
|
|
535
|
+
solved: 0,
|
|
536
|
+
authorUsd: 0
|
|
537
|
+
}]));
|
|
538
|
+
let authorCents = 0, feeCents = 0, solved = 0, uses = 0;
|
|
539
|
+
for (const tx of store.ledger) {
|
|
540
|
+
const item = packs.get(tx.packId);
|
|
541
|
+
if (!item) continue;
|
|
542
|
+
uses++;
|
|
543
|
+
item.uses++;
|
|
544
|
+
if (tx.result === "solved") {
|
|
545
|
+
solved++;
|
|
546
|
+
item.solved++;
|
|
547
|
+
}
|
|
548
|
+
authorCents += Math.round(tx.authorUsd * 100);
|
|
549
|
+
feeCents += Math.round(tx.feeUsd * 100);
|
|
550
|
+
item.authorUsd = (Math.round(item.authorUsd * 100) + Math.round(tx.authorUsd * 100)) / 100;
|
|
551
|
+
}
|
|
552
|
+
return {
|
|
553
|
+
uses,
|
|
554
|
+
solved,
|
|
555
|
+
authorUsd: authorCents / 100,
|
|
556
|
+
feeUsd: feeCents / 100,
|
|
557
|
+
byPack: [...packs.values()]
|
|
558
|
+
};
|
|
559
|
+
}
|
|
560
|
+
// ../core/src/links.ts
|
|
561
|
+
function resolveLink(target, ids) {
|
|
562
|
+
if (ids.includes(target)) return target;
|
|
563
|
+
const basename = (value) => value.split(/[\\/]/).pop().replace(/\.md$/i, "");
|
|
564
|
+
const name = basename(target);
|
|
565
|
+
const matches = ids.filter((id) => basename(id) === name);
|
|
566
|
+
return matches.length === 1 ? matches[0] : void 0;
|
|
567
|
+
}
|
|
568
|
+
// ../core/src/prune.ts
|
|
569
|
+
function classifyParagraphs(pages) {
|
|
570
|
+
const incoming = /* @__PURE__ */ new Map();
|
|
571
|
+
const ids = pages.map((page) => page.id);
|
|
572
|
+
for (const page of pages) for (const link of new Set(page.links)) {
|
|
573
|
+
const target = resolveLink(link, ids);
|
|
574
|
+
if (target === void 0 || target === page.id) continue;
|
|
575
|
+
const sources = incoming.get(target) ?? [];
|
|
576
|
+
sources.push(page);
|
|
577
|
+
incoming.set(target, sources);
|
|
578
|
+
}
|
|
579
|
+
return pages.flatMap((page) => {
|
|
580
|
+
const sources = incoming.get(page.id) ?? [];
|
|
581
|
+
const needsContextReview = sources.length > 0 && sources.every((source) => source.class === "personal" || source.class === "customer");
|
|
582
|
+
return page.markdown.split(/\r?\n[\t ]*\r?\n/).map((text) => text.trim()).filter(Boolean).map((markdown, index) => {
|
|
583
|
+
const kind = classify({
|
|
584
|
+
...page,
|
|
585
|
+
markdown
|
|
586
|
+
});
|
|
587
|
+
const reason = needsContextReview ? "Only personal or customer pages link to this page." : {
|
|
588
|
+
secret: "Contains sensitive data.",
|
|
589
|
+
customer: "Matches customer information.",
|
|
590
|
+
personal: "Matches personal notes.",
|
|
591
|
+
purchased: "Imported from a purchased pack.",
|
|
592
|
+
expertise: "No personal, customer, or secret rule matched."
|
|
593
|
+
}[kind];
|
|
594
|
+
return {
|
|
595
|
+
id: `${page.id}#${index + 1}`,
|
|
596
|
+
pageId: page.id,
|
|
597
|
+
markdown,
|
|
598
|
+
class: kind,
|
|
599
|
+
confidence: needsContextReview ? .6 : .95,
|
|
600
|
+
reason,
|
|
601
|
+
keep: kind === "expertise",
|
|
602
|
+
confirmed: false
|
|
603
|
+
};
|
|
604
|
+
});
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
function hasUnconfirmedParagraphs(paragraphs) {
|
|
608
|
+
return paragraphs.some((paragraph) => paragraph.confidence < .7 && !paragraph.confirmed);
|
|
609
|
+
}
|
|
610
|
+
function passesPruning(paragraphs) {
|
|
611
|
+
return !hasUnconfirmedParagraphs(paragraphs) && !paragraphs.some((paragraph) => paragraph.keep && (paragraph.class === "customer" || paragraph.class === "secret" || paragraph.class === "purchased"));
|
|
612
|
+
}
|
|
613
|
+
// ../core/src/distill.ts
|
|
614
|
+
var fields = [
|
|
615
|
+
"symptom",
|
|
616
|
+
"cause",
|
|
617
|
+
"fix",
|
|
618
|
+
"avoid",
|
|
619
|
+
"verify"
|
|
620
|
+
];
|
|
621
|
+
var headings = [
|
|
622
|
+
["symptom", /症状|symptom/i],
|
|
623
|
+
["cause", /原因|cause/i],
|
|
624
|
+
["fix", /直し方|fix/i],
|
|
625
|
+
["avoid", /避ける|avoid/i],
|
|
626
|
+
["verify", /確認|verify/i]
|
|
627
|
+
];
|
|
628
|
+
function distill(pages, paragraphs = classifyParagraphs(pages), dictionary) {
|
|
629
|
+
const result = {
|
|
630
|
+
fields: {
|
|
631
|
+
symptom: [],
|
|
632
|
+
cause: [],
|
|
633
|
+
fix: [],
|
|
634
|
+
avoid: [],
|
|
635
|
+
verify: []
|
|
636
|
+
},
|
|
637
|
+
errorSignatures: [],
|
|
638
|
+
sourceIds: [],
|
|
639
|
+
nodes: []
|
|
640
|
+
};
|
|
641
|
+
for (const page of pages.filter((item) => item.keep)) {
|
|
642
|
+
result.nodes.push({
|
|
643
|
+
id: page.id,
|
|
644
|
+
links: page.links
|
|
645
|
+
});
|
|
646
|
+
let current;
|
|
647
|
+
for (const paragraph of paragraphs.filter((item) => item.pageId === page.id)) {
|
|
648
|
+
const sourceId = paragraph.id;
|
|
649
|
+
if (paragraph.keep) result.sourceIds.push(sourceId);
|
|
650
|
+
let text = [];
|
|
651
|
+
const flush = () => {
|
|
652
|
+
const content = text.join("\n").trim();
|
|
653
|
+
if (paragraph.keep && current && content) result.fields[current].push({
|
|
654
|
+
text: content,
|
|
655
|
+
sourceId
|
|
656
|
+
});
|
|
657
|
+
text = [];
|
|
658
|
+
};
|
|
659
|
+
for (const line of paragraph.markdown.split(/\r?\n/)) {
|
|
660
|
+
const heading = /^##\s+(.+?)\s*#*\s*$/.exec(line);
|
|
661
|
+
if (heading) {
|
|
662
|
+
flush();
|
|
663
|
+
current = headings.find(([, pattern]) => pattern.test(heading[1]))?.[0];
|
|
664
|
+
} else text.push(line);
|
|
665
|
+
}
|
|
666
|
+
flush();
|
|
667
|
+
}
|
|
668
|
+
}
|
|
669
|
+
const keptIds = new Set(pages.filter((page) => page.keep && page.class !== "purchased").map((page) => page.id));
|
|
670
|
+
const retained = paragraphs.filter((paragraph) => paragraph.keep && paragraph.class === "expertise" && keptIds.has(paragraph.pageId));
|
|
671
|
+
const retainedIds = new Set(retained.map((paragraph) => paragraph.pageId));
|
|
672
|
+
const derived = buildForbiddenDictionary(pages.filter((page) => !retainedIds.has(page.id)), retained.map((paragraph) => paragraph.markdown));
|
|
673
|
+
const forbidden = {
|
|
674
|
+
terms: [.../* @__PURE__ */ new Set([...derived.terms, ...dictionary?.terms ?? []])],
|
|
675
|
+
shared: []
|
|
676
|
+
};
|
|
677
|
+
const candidates = retained.flatMap((paragraph) => paragraph.markdown.replace(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/, "").split(/\r?\n/).filter((line) => !/^\s*#/.test(line)).join(" ").split(/(?<=[。!?!?])\s*|(?<=\.)\s+/).map((text) => text.trim()).filter((text) => text && rescan(text, forbidden) === 0).map((text) => ({
|
|
678
|
+
text,
|
|
679
|
+
sourceId: paragraph.id,
|
|
680
|
+
confidence: .5
|
|
681
|
+
})));
|
|
682
|
+
result.fallbackCandidates = fields.filter((field) => result.fields[field].length === 0).flatMap((field) => candidates.slice(0, 5).map((candidate) => ({
|
|
683
|
+
field,
|
|
684
|
+
...candidate
|
|
685
|
+
})));
|
|
686
|
+
const signatures = (result.fields.symptom.length ? result.fields.symptom : result.fallbackCandidates.filter((candidate) => candidate.field === "symptom")).flatMap(({ text }) => text.split(/[\n。.!?]+/));
|
|
687
|
+
result.errorSignatures = [...new Set(signatures.map((value) => value.replace(/\S*[\\/]\S*/g, " ").replace(/\d+/g, " ").replace(/\s+/g, " ").trim()).filter((value) => Boolean(value) && rescan(value, forbidden) === 0))].slice(0, 5);
|
|
688
|
+
return result;
|
|
689
|
+
}
|
|
690
|
+
function distilledMarkdown(pack) {
|
|
691
|
+
return fields.map((field) => `## ${field}\n\n${pack.fields[field].flatMap(({ text, sourceId }) => text.split(/(?<=[。!?!?])\s*|(?<=\.)\s+|\n+/).map((sentence) => sentence.trim()).filter(Boolean).map((sentence) => `${sentence} [${sourceId}]`)).join("\n\n")}`).join("\n\n");
|
|
692
|
+
}
|
|
693
|
+
function pageGraph(nodes) {
|
|
694
|
+
const ids = [...new Set(nodes.map(({ id }) => id))];
|
|
695
|
+
const graph = new Map(ids.map((id) => [id, /* @__PURE__ */ new Set()]));
|
|
696
|
+
for (const node of nodes) for (const target of node.links) {
|
|
697
|
+
const resolved = resolveLink(target, ids);
|
|
698
|
+
if (resolved !== void 0 && resolved !== node.id) {
|
|
699
|
+
graph.get(node.id).add(resolved);
|
|
700
|
+
graph.get(resolved).add(node.id);
|
|
701
|
+
}
|
|
702
|
+
}
|
|
703
|
+
return graph;
|
|
704
|
+
}
|
|
705
|
+
function checkDistillation(pack) {
|
|
706
|
+
const sources = new Set(pack.sourceIds);
|
|
707
|
+
const cited = fields.flatMap((field) => pack.fields[field]).every(({ text, sourceId }) => !text.trim() || Boolean(sourceId.trim()) && sources.has(sourceId));
|
|
708
|
+
const withinLength = distilledMarkdown(pack).length / 4 <= 2e3;
|
|
709
|
+
const isolatedPageIds = [...pageGraph(pack.nodes)].filter(([, neighbors]) => neighbors.size === 0).map(([id]) => id);
|
|
710
|
+
const connected = pack.nodes.length > 0 && isolatedPageIds.length === 0;
|
|
711
|
+
return {
|
|
712
|
+
cited,
|
|
713
|
+
withinLength,
|
|
714
|
+
connected,
|
|
715
|
+
isolatedPageIds,
|
|
716
|
+
passed: cited && withinLength && connected
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
function evaluateStatic({ pack, testNames, testCode, dictionary }) {
|
|
720
|
+
const body = distilledMarkdown(pack);
|
|
721
|
+
const check = checkDistillation(pack);
|
|
722
|
+
const format = fields.every((field) => pack.fields[field].some(({ text }) => Boolean(text.trim()))) && pack.errorSignatures.length >= 3 && pack.errorSignatures.length <= 5 && pack.errorSignatures.every((value) => Boolean(value.trim()) && !/[\d\\/]/.test(value)) && check.connected;
|
|
723
|
+
const citations = check.cited;
|
|
724
|
+
const clean = rescan(body, dictionary) === 0;
|
|
725
|
+
const length = check.withinLength;
|
|
726
|
+
const copying = [...testNames, ...testCode].every((value) => !value.trim() || !body.includes(value));
|
|
727
|
+
return {
|
|
728
|
+
format,
|
|
729
|
+
citations,
|
|
730
|
+
rescan: clean,
|
|
731
|
+
length,
|
|
732
|
+
copying,
|
|
733
|
+
isolatedPageIds: check.isolatedPageIds,
|
|
734
|
+
passed: format && citations && clean && length && copying
|
|
735
|
+
};
|
|
736
|
+
}
|
|
737
|
+
function evaluateKeywords(markdown, keywords) {
|
|
738
|
+
const missing = keywords.filter((keyword) => !keyword || !markdown.includes(keyword));
|
|
739
|
+
return {
|
|
740
|
+
passed: keywords.length > 0 && missing.length === 0,
|
|
741
|
+
missing
|
|
742
|
+
};
|
|
743
|
+
}
|
|
744
|
+
// ../core/src/import-files.ts
|
|
745
|
+
function safeSegment(value) {
|
|
746
|
+
return typeof value === "string" && value.length > 0 && value !== "." && value !== ".." && !Array.from(value).some((char) => char.charCodeAt(0) < 32 || char.charCodeAt(0) === 127 || "<>:\"/\\|?*[]".includes(char)) && !/[. ]$/.test(value) && !/^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\.|$)/i.test(value);
|
|
747
|
+
}
|
|
748
|
+
function pathKey(path) {
|
|
749
|
+
return path.replace(/\\/g, "/").replace(/^\.\//, "").normalize("NFC").toLowerCase();
|
|
750
|
+
}
|
|
751
|
+
function buildImportFiles(pack, purchasedAt) {
|
|
752
|
+
if (!safeSegment(pack.id) || typeof pack.version !== "string" || typeof pack.summary !== "string" || typeof purchasedAt !== "string" || !Array.isArray(pack.pages)) throw new Error("Invalid import pack");
|
|
753
|
+
if (rescan(pack.summary) || pack.pages.some((page) => page && typeof page.markdown === "string" && rescan(page.markdown))) throw new Error("Sensitive data in import pack");
|
|
754
|
+
const prefix = `packs/${pack.id}`;
|
|
755
|
+
const paths = /* @__PURE__ */ new Set([pathKey(`${prefix}/index.md`)]);
|
|
756
|
+
const header = `---\nsource: gbrainx\npack: ${JSON.stringify(pack.id)}\nversion: ${JSON.stringify(pack.version)}\nlicense: personal-use\npurchasedAt: ${JSON.stringify(purchasedAt)}\n---\n\n`;
|
|
757
|
+
const pages = pack.pages.map((page) => {
|
|
758
|
+
if (!page || !safeSegment(page.id) || typeof page.markdown !== "string") throw new Error("Invalid import page");
|
|
759
|
+
const path = `${prefix}/${page.id}.md`;
|
|
760
|
+
const key = pathKey(path);
|
|
761
|
+
if (paths.has(key)) throw new Error("Duplicate import path");
|
|
762
|
+
paths.add(key);
|
|
763
|
+
return {
|
|
764
|
+
path,
|
|
765
|
+
markdown: header + page.markdown
|
|
766
|
+
};
|
|
767
|
+
});
|
|
768
|
+
const links = pack.pages.map(({ id }) => `- [[${id}]]`).join("\n");
|
|
769
|
+
return [{
|
|
770
|
+
path: `${prefix}/index.md`,
|
|
771
|
+
markdown: header + pack.summary + (links ? `\n\n${links}` : "") + "\n"
|
|
772
|
+
}, ...pages];
|
|
773
|
+
}
|
|
774
|
+
function findImportConflicts(files, existingPaths) {
|
|
775
|
+
const existing = new Set(existingPaths.map(pathKey));
|
|
776
|
+
return files.filter(({ path }) => existing.has(pathKey(path))).map(({ path }) => path);
|
|
777
|
+
}
|
|
778
|
+
// ../core/src/store.ts
|
|
779
|
+
var STORE_KEY = "gbrainx:v1";
|
|
780
|
+
var STORE_MAX_BYTES = 4194304;
|
|
781
|
+
var object = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
782
|
+
var string = (value) => typeof value === "string";
|
|
783
|
+
var strings = (value) => Array.isArray(value) && value.every(string);
|
|
784
|
+
var oneOf = (value, choices) => string(value) && choices.includes(value);
|
|
785
|
+
var unique = (items) => new Set(items.map((item) => item.id)).size === items.length;
|
|
786
|
+
function validPage(value) {
|
|
787
|
+
return object(value) && string(value.id) && string(value.title) && string(value.markdown) && strings(value.links) && oneOf(value.class, [
|
|
788
|
+
"expertise",
|
|
789
|
+
"personal",
|
|
790
|
+
"customer",
|
|
791
|
+
"secret",
|
|
792
|
+
"purchased"
|
|
793
|
+
]) && typeof value.keep === "boolean";
|
|
794
|
+
}
|
|
795
|
+
function validPack(value) {
|
|
796
|
+
return object(value) && string(value.id) && string(value.title) && string(value.version) && string(value.domain) && strings(value.errorSignatures) && strings(value.nodes) && string(value.markdown) && string(value.summary) && value.summary.length <= 2e3 && Array.isArray(value.pages) && value.pages.every((page) => object(page) && string(page.id) && string(page.markdown)) && Array.isArray(value.scrubbed) && value.scrubbed.every((entry) => object(entry) && string(entry.kind) && typeof entry.count === "number" && Number.isSafeInteger(entry.count) && entry.count >= 0) && object(value.eval) && string(value.eval.without) && string(value.eval.with) && value.eval.recorded === true && isMoney(value.priceUsd) && oneOf(value.author, ["you", "seed"]) && string(value.createdAt);
|
|
797
|
+
}
|
|
798
|
+
function validTx(value) {
|
|
799
|
+
return object(value) && string(value.id) && string(value.packId) && string(value.sessionId) && string(value.at) && isMoney(value.amountUsd) && isMoney(value.authorUsd) && isMoney(value.feeUsd) && oneOf(value.via, ["web", "mcp"]) && oneOf(value.result, [
|
|
800
|
+
"running",
|
|
801
|
+
"solved",
|
|
802
|
+
"unsolved"
|
|
803
|
+
]) && strings(value.pagesUsed);
|
|
804
|
+
}
|
|
805
|
+
function validSession(value) {
|
|
806
|
+
return object(value) && string(value.id) && string(value.startedAt) && isMoney(value.spentUsd) && Array.isArray(value.calls) && value.calls.every((call) => object(call) && oneOf(call.tool, [
|
|
807
|
+
"search",
|
|
808
|
+
"buy",
|
|
809
|
+
"load"
|
|
810
|
+
]) && string(call.at) && string(call.summary) && (call.tool === "buy" ? string(call.txId) : call.txId === void 0 || string(call.txId)));
|
|
811
|
+
}
|
|
812
|
+
function validateStore(value) {
|
|
813
|
+
if (!object(value) || value.version !== 1 || typeof value.rev !== "number" || !Number.isSafeInteger(value.rev) || value.rev < 0 || !object(value.brain) || !Array.isArray(value.brain.pages) || !value.brain.pages.every(validPage) || !Array.isArray(value.packs) || !value.packs.every(validPack) || !unique(value.packs) || !object(value.wallet) || !isMoney(value.wallet.buyerUsd) || !isMoney(value.wallet.perPurchaseCapUsd) || !isMoney(value.wallet.sessionCapUsd) || !Array.isArray(value.ledger) || !value.ledger.every(validTx) || !unique(value.ledger) || !Array.isArray(value.sessions) || !value.sessions.every(validSession) || !unique(value.sessions)) return false;
|
|
814
|
+
return true;
|
|
815
|
+
}
|
|
816
|
+
function utf8Length(text) {
|
|
817
|
+
let length = 0;
|
|
818
|
+
for (const char of text) {
|
|
819
|
+
const point = char.codePointAt(0);
|
|
820
|
+
length += point <= 127 ? 1 : point <= 2047 ? 2 : point <= 65535 ? 3 : 4;
|
|
821
|
+
if (length > 4194304) return length;
|
|
822
|
+
}
|
|
823
|
+
return length;
|
|
824
|
+
}
|
|
825
|
+
function parseStore(json) {
|
|
826
|
+
if (typeof json !== "string" || utf8Length(json) > 4194304) throw new Error("Invalid store size");
|
|
827
|
+
const value = JSON.parse(json);
|
|
828
|
+
if (!validateStore(value)) throw new Error("Invalid store");
|
|
829
|
+
return value;
|
|
830
|
+
}
|
|
831
|
+
function serializeStore(store) {
|
|
832
|
+
if (!validateStore(store)) throw new Error("Invalid store");
|
|
833
|
+
const json = JSON.stringify(store);
|
|
834
|
+
if (utf8Length(json) > 4194304) throw new Error("Invalid store size");
|
|
835
|
+
return json;
|
|
836
|
+
}
|
|
837
|
+
// ../core/src/index.ts
|
|
838
|
+
function scrub(markdown) {
|
|
839
|
+
const result = scrubDetailed(markdown);
|
|
840
|
+
return {
|
|
841
|
+
markdown: result.markdown.replace(/\[REDACTED_([A-Z_]+)_\d+\]/g, (match, kind) => kind === "NAME" ? match : `[REDACTED_${kind}]`),
|
|
842
|
+
scrubbed: result.scrubbed,
|
|
843
|
+
remaining: result.remaining
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
function isPurchased(markdown) {
|
|
847
|
+
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown)?.[1];
|
|
848
|
+
return frontmatter !== void 0 && /^source[ \t]*:[ \t]*(?:gbrainx|"gbrainx"|'gbrainx')[ \t]*(?:#.*)?$/m.test(frontmatter);
|
|
849
|
+
}
|
|
850
|
+
function classify(page) {
|
|
851
|
+
if (page.class === "purchased" || isPurchased(page.markdown)) return "purchased";
|
|
852
|
+
const scrubbed = scrubDetailed(page.markdown);
|
|
853
|
+
const sensitive = (kind) => kind !== "HOME_PATH" && kind !== "GBRAIN_PATH" && kind !== "SOURCE";
|
|
854
|
+
if (scrubbed.scrubbed.some(({ kind }) => sensitive(kind)) || scrubbed.changes.some(({ kind, before }) => (kind === "SOURCE" || kind === "GBRAIN_PATH") && scrubDetailed(kind === "GBRAIN_PATH" ? before.replace(/^~[\\/]\.gbrain[\\/]?/i, "") : before).scrubbed.some((entry) => sensitive(entry.kind)))) return "secret";
|
|
855
|
+
const phone = [...page.markdown.matchAll(/\+?\d[\d ()-]*/g)].some((match) => {
|
|
856
|
+
let candidate = match[0].trimEnd();
|
|
857
|
+
let end = candidate.length;
|
|
858
|
+
while (end > 0 && (candidate[end - 1] === "-" || candidate[end - 1] === "(")) end--;
|
|
859
|
+
candidate = candidate.slice(0, end).trimEnd();
|
|
860
|
+
const before = page.markdown[match.index - 1] ?? "";
|
|
861
|
+
const after = page.markdown[match.index + candidate.length] ?? "";
|
|
862
|
+
const digits = candidate.replace(/\D/g, "").length;
|
|
863
|
+
return !/[A-Za-z0-9-]/.test(before) && !/[A-Za-z0-9-]/.test(after) && !/^\d{4}-\d{2}-\d{2}$/.test(candidate) && /[ ()+-]/.test(candidate) && digits >= 9 && digits <= 15;
|
|
864
|
+
});
|
|
865
|
+
if (/^customer-/i.test(page.id) || phone) return "customer";
|
|
866
|
+
if (/standup|1on1|oncall|retro|休暇/i.test(`${page.id}\n${page.markdown}`)) return "personal";
|
|
867
|
+
return "expertise";
|
|
868
|
+
}
|
|
869
|
+
function parse(files) {
|
|
870
|
+
return files.filter(({ name }) => /\.md$/i.test(name)).map(({ name, markdown }) => {
|
|
871
|
+
const id = name.split(/[\\/]/).pop().replace(/\.md$/i, "");
|
|
872
|
+
const page = {
|
|
873
|
+
id,
|
|
874
|
+
title: /^#\s+(.+)$/m.exec(markdown)?.[1].trim() || id,
|
|
875
|
+
markdown,
|
|
876
|
+
links: [...markdown.matchAll(/\[\[([^\][|]+)(?:\|[^\][]*)?\]\]/g)].map((match) => match[1].trim()),
|
|
877
|
+
class: "expertise",
|
|
878
|
+
keep: true
|
|
879
|
+
};
|
|
880
|
+
page.class = classify(page);
|
|
881
|
+
page.keep = page.class === "expertise";
|
|
882
|
+
return page;
|
|
883
|
+
});
|
|
884
|
+
}
|
|
885
|
+
var StaticEvaluationError = class extends Error {
|
|
886
|
+
issues;
|
|
887
|
+
constructor(issues, message = "Static evaluation failed") {
|
|
888
|
+
super(message);
|
|
889
|
+
this.issues = issues;
|
|
890
|
+
this.name = "StaticEvaluationError";
|
|
891
|
+
}
|
|
892
|
+
};
|
|
893
|
+
function buildPack(pages, input) {
|
|
894
|
+
if (!input.staticEvaluation || !Array.isArray(input.staticEvaluation.testNames) || !Array.isArray(input.staticEvaluation.testCode) || !Array.isArray(input.staticEvaluation.keywords) || !input.staticEvaluation.distilled) throw new StaticEvaluationError([{ code: "invalid_input" }], "Static evaluation input is required");
|
|
895
|
+
const { testNames, testCode, keywords } = input.staticEvaluation;
|
|
896
|
+
if (![...testNames, ...testCode].some((value) => typeof value === "string" && value.trim()) || [...testNames, ...testCode].some((value) => typeof value !== "string")) throw new StaticEvaluationError([{ code: "invalid_input" }], "Static evaluation input is required");
|
|
897
|
+
const signatures = input.errorSignatures.map((value) => value.trim()).filter(Boolean);
|
|
898
|
+
if (!signatures.length) throw new Error("At least one error signature is required");
|
|
899
|
+
if (!input.title.trim()) throw new Error("A title is required");
|
|
900
|
+
let hash = 14695981039346656037n;
|
|
901
|
+
for (const char of input.title) {
|
|
902
|
+
hash ^= BigInt(char.codePointAt(0));
|
|
903
|
+
hash = BigInt.asUintN(64, hash * 1099511628211n);
|
|
904
|
+
}
|
|
905
|
+
const baseId = input.title.toLowerCase().trim().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "") || `pack-${hash.toString(36)}`;
|
|
906
|
+
const existingIds = new Set(input.existingIds ?? []);
|
|
907
|
+
let id = baseId;
|
|
908
|
+
for (let suffix = 2; existingIds.has(id); suffix++) id = `${baseId}-${suffix}`;
|
|
909
|
+
if (typeof input.eval !== "object" || input.eval === null || Object.keys(input.eval).sort().join(",") !== "recorded,with,without" || typeof input.eval.without !== "string" || typeof input.eval.with !== "string" || input.eval.recorded !== true) throw new Error("Invalid evaluation");
|
|
910
|
+
if (input.author !== void 0 && input.author !== "you" && input.author !== "seed") throw new Error("Invalid author");
|
|
911
|
+
const priceUsd = input.priceUsd === void 0 ? .5 : input.priceUsd;
|
|
912
|
+
if (!Number.isFinite(priceUsd) || priceUsd < 0) throw new Error("Invalid price");
|
|
913
|
+
const kept = pages.filter((page) => page.keep && page.class !== "purchased" && !isPurchased(page.markdown));
|
|
914
|
+
if (!kept.length) throw new Error("At least one kept page is required");
|
|
915
|
+
const retainedIds = new Set(kept.map((page) => page.id));
|
|
916
|
+
const derivedDictionary = buildForbiddenDictionary(pages.filter((page) => !retainedIds.has(page.id)), kept.map((page) => page.markdown));
|
|
917
|
+
const dictionary = {
|
|
918
|
+
terms: [.../* @__PURE__ */ new Set([...derivedDictionary.terms, ...input.forbiddenDictionary?.terms ?? []])],
|
|
919
|
+
shared: [.../* @__PURE__ */ new Set([...derivedDictionary.shared, ...input.forbiddenDictionary?.shared ?? []])]
|
|
920
|
+
};
|
|
921
|
+
const normalize = (value) => value.replace(/\[REDACTED_([A-Z_]+)_\d+\]/g, (match, kind) => kind === "NAME" ? match : `[REDACTED_${kind}]`);
|
|
922
|
+
const scrubPackText = (value) => {
|
|
923
|
+
const result = scrubDetailed(value, dictionary);
|
|
924
|
+
return {
|
|
925
|
+
...result,
|
|
926
|
+
markdown: normalize(result.markdown)
|
|
927
|
+
};
|
|
928
|
+
};
|
|
929
|
+
const checkRemaining = (value, remaining, location) => {
|
|
930
|
+
if (!remaining) return;
|
|
931
|
+
const issues = [];
|
|
932
|
+
if (scrubDetailed(value, dictionary).changes.some(({ kind }) => kind === "NAME")) issues.push({
|
|
933
|
+
code: "forbidden_term",
|
|
934
|
+
location
|
|
935
|
+
});
|
|
936
|
+
if (rescan(value) > 0 || !issues.length) issues.push({
|
|
937
|
+
code: "rescan",
|
|
938
|
+
location
|
|
939
|
+
});
|
|
940
|
+
throw new StaticEvaluationError(issues, "Sensitive data remains after scrubbing");
|
|
941
|
+
};
|
|
942
|
+
const evidence = () => ({
|
|
943
|
+
generated: /* @__PURE__ */ new Set(),
|
|
944
|
+
existing: /* @__PURE__ */ new Set()
|
|
945
|
+
});
|
|
946
|
+
const remember = (target, original, changes) => {
|
|
947
|
+
for (const match of original.matchAll(/\[REDACTED_[A-Z_]+(?:_\d+)?\]|~\//g)) target.existing.add(normalize(match[0]));
|
|
948
|
+
for (const change of changes) target.generated.add(change.kind === "HOME_PATH" ? "~/" : normalize(change.after));
|
|
949
|
+
};
|
|
950
|
+
const metadata = [
|
|
951
|
+
input.title,
|
|
952
|
+
input.version,
|
|
953
|
+
input.domain,
|
|
954
|
+
...input.errorSignatures,
|
|
955
|
+
input.eval.without,
|
|
956
|
+
input.eval.with,
|
|
957
|
+
input.createdAt,
|
|
958
|
+
...kept.map((page) => page.id)
|
|
959
|
+
];
|
|
960
|
+
const metadataIssues = [];
|
|
961
|
+
if (metadata.some((value) => scrubDetailed(value, dictionary).changes.some(({ kind }) => kind === "NAME"))) metadataIssues.push({
|
|
962
|
+
code: "forbidden_term",
|
|
963
|
+
location: "metadata"
|
|
964
|
+
});
|
|
965
|
+
if (metadata.some((value) => scrub(value).scrubbed.length > 0)) metadataIssues.push({
|
|
966
|
+
code: "rescan",
|
|
967
|
+
location: "metadata"
|
|
968
|
+
});
|
|
969
|
+
if (metadataIssues.length) throw new StaticEvaluationError(metadataIssues, "Sensitive data in pack metadata");
|
|
970
|
+
const byId = new Map(kept.map((page) => [page.id, page]));
|
|
971
|
+
if (byId.size !== kept.length) throw new Error("Duplicate page id");
|
|
972
|
+
const ids = [...byId.keys()];
|
|
973
|
+
const ordered = [];
|
|
974
|
+
const visited = /* @__PURE__ */ new Set();
|
|
975
|
+
for (const page of kept) {
|
|
976
|
+
const pending = [page];
|
|
977
|
+
while (pending.length) {
|
|
978
|
+
const next = pending.pop();
|
|
979
|
+
if (visited.has(next.id)) continue;
|
|
980
|
+
visited.add(next.id);
|
|
981
|
+
ordered.push(next);
|
|
982
|
+
for (let i = next.links.length - 1; i >= 0; i--) {
|
|
983
|
+
const target = resolveLink(next.links[i], ids);
|
|
984
|
+
const linked = target === void 0 ? void 0 : byId.get(target);
|
|
985
|
+
if (linked) pending.push(linked);
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
const result = scrubPackText(`${ordered.map((page) => `## [[${page.id}]]\n\n${page.markdown}`).join("\n\n")}\n\n## Sources\n\n${ordered.map((page) => `- [[${page.id}]]`).join("\n")}`);
|
|
990
|
+
checkRemaining(result.markdown, result.remaining, "markdown");
|
|
991
|
+
const pageEvidence = /* @__PURE__ */ new Map();
|
|
992
|
+
const safePages = ordered.map((page) => {
|
|
993
|
+
const sanitized = scrubPackText(page.markdown);
|
|
994
|
+
checkRemaining(sanitized.markdown, sanitized.remaining, { pageId: page.id });
|
|
995
|
+
const item = evidence();
|
|
996
|
+
remember(item, page.markdown, sanitized.changes);
|
|
997
|
+
pageEvidence.set(page.id, item);
|
|
998
|
+
return {
|
|
999
|
+
id: page.id,
|
|
1000
|
+
markdown: sanitized.markdown
|
|
1001
|
+
};
|
|
1002
|
+
});
|
|
1003
|
+
const fields = [
|
|
1004
|
+
"symptom",
|
|
1005
|
+
"cause",
|
|
1006
|
+
"fix",
|
|
1007
|
+
"avoid",
|
|
1008
|
+
"verify"
|
|
1009
|
+
];
|
|
1010
|
+
const provided = input.staticEvaluation.distilled;
|
|
1011
|
+
const validSources = new Set(classifyParagraphs(ordered).filter((paragraph) => paragraph.class === "expertise" || paragraph.class === "personal").map((paragraph) => paragraph.id));
|
|
1012
|
+
if (!provided.fields || !Array.isArray(provided.errorSignatures) || signatures.join("\n") !== provided.errorSignatures.join("\n")) throw new StaticEvaluationError([{ code: "invalid_input" }]);
|
|
1013
|
+
const sanitizedFields = {};
|
|
1014
|
+
const summaryEvidence = evidence();
|
|
1015
|
+
const malformed = [];
|
|
1016
|
+
for (const field of fields) {
|
|
1017
|
+
if (!Array.isArray(provided.fields[field])) {
|
|
1018
|
+
malformed.push({ code: "invalid_input" });
|
|
1019
|
+
continue;
|
|
1020
|
+
}
|
|
1021
|
+
sanitizedFields[field] = provided.fields[field].flatMap((entry) => {
|
|
1022
|
+
if (!entry || typeof entry.text !== "string" || typeof entry.sourceId !== "string") {
|
|
1023
|
+
malformed.push({ code: "invalid_input" });
|
|
1024
|
+
return [];
|
|
1025
|
+
}
|
|
1026
|
+
if (!validSources.has(entry.sourceId)) {
|
|
1027
|
+
malformed.push({ code: "citations" });
|
|
1028
|
+
return [];
|
|
1029
|
+
}
|
|
1030
|
+
const result = scrubPackText(entry.text);
|
|
1031
|
+
checkRemaining(result.markdown, result.remaining, "summary");
|
|
1032
|
+
remember(summaryEvidence, entry.text, result.changes);
|
|
1033
|
+
return [{
|
|
1034
|
+
text: result.markdown,
|
|
1035
|
+
sourceId: entry.sourceId
|
|
1036
|
+
}];
|
|
1037
|
+
});
|
|
1038
|
+
}
|
|
1039
|
+
if (malformed.length) throw new StaticEvaluationError(malformed.filter((issue, index) => malformed.findIndex((other) => other.code === issue.code) === index));
|
|
1040
|
+
const distilled = {
|
|
1041
|
+
fields: sanitizedFields,
|
|
1042
|
+
errorSignatures: signatures,
|
|
1043
|
+
sourceIds: [...validSources],
|
|
1044
|
+
nodes: ordered.map(({ id, links }) => ({
|
|
1045
|
+
id,
|
|
1046
|
+
links: links.map((link) => resolveLink(link, ids) ?? link)
|
|
1047
|
+
}))
|
|
1048
|
+
};
|
|
1049
|
+
while (distilledMarkdown(distilled).length > 2e3) {
|
|
1050
|
+
const longest = fields.flatMap((field) => distilled.fields[field]).reduce((a, b) => a.text.length >= b.text.length ? a : b);
|
|
1051
|
+
if (longest.text.length <= 1) throw new StaticEvaluationError([{ code: "length" }]);
|
|
1052
|
+
let end = Math.max(1, longest.text.length - (distilledMarkdown(distilled).length - 2e3) - 1);
|
|
1053
|
+
if (/[\uD800-\uDBFF]/.test(longest.text[end - 1])) end--;
|
|
1054
|
+
for (const match of longest.text.matchAll(/\[REDACTED_[A-Z_]+(?:_\d+)?\]|~\//g)) if (match.index < end && match.index + match[0].length > end) end = match.index;
|
|
1055
|
+
longest.text = longest.text.slice(0, end) + (end < longest.text.length - 1 ? "…" : "");
|
|
1056
|
+
}
|
|
1057
|
+
const summary = distilledMarkdown(distilled);
|
|
1058
|
+
const targets = [...testNames, ...testCode].filter((value) => value.trim());
|
|
1059
|
+
const evaluation = evaluateStatic({
|
|
1060
|
+
pack: distilled,
|
|
1061
|
+
testNames,
|
|
1062
|
+
testCode,
|
|
1063
|
+
dictionary
|
|
1064
|
+
});
|
|
1065
|
+
const issues = [];
|
|
1066
|
+
const connected = checkDistillation(distilled).connected;
|
|
1067
|
+
if (!connected) issues.push({ code: "connected" });
|
|
1068
|
+
if (!evaluation.format && (connected || !fields.every((field) => distilled.fields[field].some(({ text }) => Boolean(text.trim()))) || signatures.length < 3 || signatures.length > 5 || signatures.some((value) => !value.trim() || /[\d\\/]/.test(value)))) issues.push({ code: "format" });
|
|
1069
|
+
if (!evaluation.citations) issues.push({ code: "citations" });
|
|
1070
|
+
if (!evaluation.length) issues.push({ code: "length" });
|
|
1071
|
+
if (!evaluation.copying) issues.push({
|
|
1072
|
+
code: "summary_copying",
|
|
1073
|
+
location: "summary"
|
|
1074
|
+
});
|
|
1075
|
+
if (keywords.length < 2 || keywords.length > 3) issues.push({ code: "keyword_count" });
|
|
1076
|
+
const validKeywords = keywords.filter((value) => typeof value === "string" && value.trim());
|
|
1077
|
+
if (validKeywords.length !== keywords.length) issues.push({ code: "keyword_invalid" });
|
|
1078
|
+
if (validKeywords.length && !evaluateKeywords(summary, validKeywords).passed) issues.push({
|
|
1079
|
+
code: "keyword_missing",
|
|
1080
|
+
location: "summary"
|
|
1081
|
+
});
|
|
1082
|
+
if (targets.some((target) => result.markdown.includes(target))) issues.push({
|
|
1083
|
+
code: "markdown_copying",
|
|
1084
|
+
location: "markdown"
|
|
1085
|
+
});
|
|
1086
|
+
for (const page of safePages) if (targets.some((target) => page.markdown.includes(target))) issues.push({
|
|
1087
|
+
code: "page_copying",
|
|
1088
|
+
location: { pageId: page.id }
|
|
1089
|
+
});
|
|
1090
|
+
const outputs = [
|
|
1091
|
+
{
|
|
1092
|
+
text: summary,
|
|
1093
|
+
location: "summary"
|
|
1094
|
+
},
|
|
1095
|
+
{
|
|
1096
|
+
text: result.markdown,
|
|
1097
|
+
location: "markdown"
|
|
1098
|
+
},
|
|
1099
|
+
...safePages.map((page) => ({
|
|
1100
|
+
text: page.markdown,
|
|
1101
|
+
location: { pageId: page.id }
|
|
1102
|
+
}))
|
|
1103
|
+
];
|
|
1104
|
+
for (const output of outputs) {
|
|
1105
|
+
if (scrubDetailed(output.text, dictionary).changes.some(({ kind }) => kind === "NAME")) issues.push({
|
|
1106
|
+
code: "forbidden_term",
|
|
1107
|
+
location: output.location
|
|
1108
|
+
});
|
|
1109
|
+
if (rescan(output.text) > 0) issues.push({
|
|
1110
|
+
code: "rescan",
|
|
1111
|
+
location: output.location
|
|
1112
|
+
});
|
|
1113
|
+
}
|
|
1114
|
+
if (issues.length) throw new StaticEvaluationError(issues);
|
|
1115
|
+
const pack = {
|
|
1116
|
+
id,
|
|
1117
|
+
title: input.title,
|
|
1118
|
+
version: input.version,
|
|
1119
|
+
domain: input.domain,
|
|
1120
|
+
errorSignatures: signatures,
|
|
1121
|
+
nodes: ordered.map((page) => page.id),
|
|
1122
|
+
markdown: result.markdown,
|
|
1123
|
+
summary,
|
|
1124
|
+
pages: safePages,
|
|
1125
|
+
scrubbed: result.scrubbed,
|
|
1126
|
+
eval: input.eval,
|
|
1127
|
+
priceUsd,
|
|
1128
|
+
author: input.author ?? "you",
|
|
1129
|
+
createdAt: input.createdAt
|
|
1130
|
+
};
|
|
1131
|
+
return {
|
|
1132
|
+
pack,
|
|
1133
|
+
redactions: collectPackRedactions(pack, summaryEvidence, pageEvidence)
|
|
1134
|
+
};
|
|
1135
|
+
}
|
|
1136
|
+
function createPack(pages, input) {
|
|
1137
|
+
return buildPack(pages, input).pack;
|
|
1138
|
+
}
|
|
1139
|
+
function previewPackRedactions(pages, input) {
|
|
1140
|
+
return buildPack(pages, input).redactions;
|
|
1141
|
+
}
|
|
1142
|
+
function collectPackRedactions(pack, summaryEvidence, pageEvidence) {
|
|
1143
|
+
const found = [];
|
|
1144
|
+
const collect = (text, location, source) => {
|
|
1145
|
+
for (const match of text.matchAll(/\[REDACTED(?:_[A-Z0-9_]*)?\]?|~\//g)) {
|
|
1146
|
+
const symbol = match[0];
|
|
1147
|
+
const generated = source.generated.has(symbol);
|
|
1148
|
+
const existing = source.existing.has(symbol);
|
|
1149
|
+
if (symbol === "~/" && !generated) continue;
|
|
1150
|
+
const origin = generated && existing ? "ambiguous" : generated ? "generated" : "existing";
|
|
1151
|
+
if (symbol === "~/") found.push({
|
|
1152
|
+
location,
|
|
1153
|
+
symbol,
|
|
1154
|
+
kind: "HOME_PATH",
|
|
1155
|
+
origin
|
|
1156
|
+
});
|
|
1157
|
+
else {
|
|
1158
|
+
const label = /^\[REDACTED_([A-Z_]+?)(?:_\d+)?\]$/.exec(symbol);
|
|
1159
|
+
if (!label) throw new Error("Incomplete redaction marker");
|
|
1160
|
+
found.push({
|
|
1161
|
+
location,
|
|
1162
|
+
symbol,
|
|
1163
|
+
kind: label[1],
|
|
1164
|
+
origin
|
|
1165
|
+
});
|
|
1166
|
+
}
|
|
1167
|
+
}
|
|
1168
|
+
};
|
|
1169
|
+
collect(pack.summary, "summary", summaryEvidence);
|
|
1170
|
+
for (const page of pack.pages) collect(page.markdown, { pageId: page.id }, pageEvidence.get(page.id));
|
|
1171
|
+
return found;
|
|
1172
|
+
}
|
|
1173
|
+
function words(text) {
|
|
1174
|
+
const clean = text.toLowerCase().replace(/\S+/g, (word) => /[\\/]/.test(word) ? " " : word);
|
|
1175
|
+
const result = new Set(clean.match(/[a-z]+/g) ?? []);
|
|
1176
|
+
for (const match of clean.matchAll(/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]+/gu)) {
|
|
1177
|
+
const chars = Array.from(match[0]);
|
|
1178
|
+
if (chars.length === 1) result.add(chars[0]);
|
|
1179
|
+
for (let i = 0; i < chars.length - 1; i++) result.add(chars[i] + chars[i + 1]);
|
|
1180
|
+
}
|
|
1181
|
+
return result;
|
|
1182
|
+
}
|
|
1183
|
+
function similarity(a, b) {
|
|
1184
|
+
if (!a.size || !b.size) return 0;
|
|
1185
|
+
let intersection = 0;
|
|
1186
|
+
for (const word of a) if (b.has(word)) intersection++;
|
|
1187
|
+
return intersection / (a.size + b.size - intersection);
|
|
1188
|
+
}
|
|
1189
|
+
function search(query, store) {
|
|
1190
|
+
const queryWords = words(query);
|
|
1191
|
+
const owned = new Set(store.ledger.map((tx) => tx.packId));
|
|
1192
|
+
return store.packs.map((pack) => ({
|
|
1193
|
+
id: pack.id,
|
|
1194
|
+
title: pack.title,
|
|
1195
|
+
description: pack.domain,
|
|
1196
|
+
priceUsd: pack.priceUsd,
|
|
1197
|
+
owned: owned.has(pack.id),
|
|
1198
|
+
score: Math.max(0, ...[
|
|
1199
|
+
...pack.errorSignatures,
|
|
1200
|
+
pack.title,
|
|
1201
|
+
...pack.nodes
|
|
1202
|
+
].map((value) => similarity(queryWords, words(value))))
|
|
1203
|
+
})).filter(({ score }) => score >= .2).sort((a, b) => b.score - a.score).slice(0, 5);
|
|
1204
|
+
}
|
|
1205
|
+
function purchase(store, packId, sessionId, via, at, txId) {
|
|
1206
|
+
const result = buy(store, packId, sessionId, via, at, txId, store.rev, 1);
|
|
1207
|
+
if (!result.ok) return {
|
|
1208
|
+
ok: false,
|
|
1209
|
+
reason: result.code,
|
|
1210
|
+
code: result.code
|
|
1211
|
+
};
|
|
1212
|
+
return {
|
|
1213
|
+
ok: true,
|
|
1214
|
+
store: result.store,
|
|
1215
|
+
tx: result.tx
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
function createInitialStore() {
|
|
1219
|
+
const common = {
|
|
1220
|
+
scrubbed: [],
|
|
1221
|
+
eval: {
|
|
1222
|
+
without: "Not recorded",
|
|
1223
|
+
with: "Not recorded",
|
|
1224
|
+
recorded: true
|
|
1225
|
+
},
|
|
1226
|
+
author: "seed",
|
|
1227
|
+
createdAt: "2026-01-01T00:00:00.000Z"
|
|
1228
|
+
};
|
|
1229
|
+
return {
|
|
1230
|
+
version: 1,
|
|
1231
|
+
rev: 0,
|
|
1232
|
+
brain: { pages: [] },
|
|
1233
|
+
wallet: {
|
|
1234
|
+
buyerUsd: 10,
|
|
1235
|
+
perPurchaseCapUsd: 1,
|
|
1236
|
+
sessionCapUsd: 3
|
|
1237
|
+
},
|
|
1238
|
+
ledger: [],
|
|
1239
|
+
sessions: [],
|
|
1240
|
+
packs: [{
|
|
1241
|
+
...common,
|
|
1242
|
+
id: "stripe-webhook-signature-errors",
|
|
1243
|
+
title: "Stripe Webhook Signature Errors",
|
|
1244
|
+
version: "v3",
|
|
1245
|
+
domain: "payments",
|
|
1246
|
+
errorSignatures: ["webhook signature verification failed", "raw body parsing"],
|
|
1247
|
+
nodes: ["stripe-webhook-signature", "raw-body-parsing"],
|
|
1248
|
+
markdown: "Verify the webhook signature against the raw request body.",
|
|
1249
|
+
summary: "Verify the webhook signature against the raw request body.",
|
|
1250
|
+
pages: [{
|
|
1251
|
+
id: "stripe-webhook-signature",
|
|
1252
|
+
markdown: "Verify the webhook signature against the raw request body."
|
|
1253
|
+
}, {
|
|
1254
|
+
id: "raw-body-parsing",
|
|
1255
|
+
markdown: "Keep the raw request body for verification."
|
|
1256
|
+
}],
|
|
1257
|
+
priceUsd: .5
|
|
1258
|
+
}, {
|
|
1259
|
+
...common,
|
|
1260
|
+
id: "postgres-zero-downtime-migrations",
|
|
1261
|
+
title: "Postgres Zero-Downtime Migrations",
|
|
1262
|
+
version: "v2",
|
|
1263
|
+
domain: "data",
|
|
1264
|
+
errorSignatures: ["database migration downtime", "add column safely"],
|
|
1265
|
+
nodes: ["pg-add-column-safely"],
|
|
1266
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints.",
|
|
1267
|
+
summary: "Add columns in stages and migrate data before enforcing constraints.",
|
|
1268
|
+
pages: [{
|
|
1269
|
+
id: "pg-add-column-safely",
|
|
1270
|
+
markdown: "Add columns in stages and migrate data before enforcing constraints."
|
|
1271
|
+
}],
|
|
1272
|
+
priceUsd: .8
|
|
1273
|
+
}]
|
|
1274
|
+
};
|
|
1275
|
+
}
|
|
1276
|
+
function createSkillMarkdown(pack) {
|
|
1277
|
+
const suffix = " のときに使う。";
|
|
1278
|
+
const prefix = `${pack.domain} の専門知識。`;
|
|
1279
|
+
if (prefix.length + 8 > 1e3) throw new Error("Domain is too long");
|
|
1280
|
+
let signatures = pack.errorSignatures.slice(0, 2).join("、").slice(0, 1e3 - prefix.length - 8);
|
|
1281
|
+
if (/[\uD800-\uDBFF]$/.test(signatures)) signatures = signatures.slice(0, -1);
|
|
1282
|
+
const description = prefix + signatures + suffix;
|
|
1283
|
+
return scrub(`---\nname: ${JSON.stringify(pack.id)}\ndescription: ${JSON.stringify(description)}\n---\n\n${pack.markdown}\n`).markdown;
|
|
1284
|
+
}
|
|
1285
|
+
function utf8(value) {
|
|
1286
|
+
const bytes = [];
|
|
1287
|
+
for (const char of value) {
|
|
1288
|
+
let code = char.codePointAt(0);
|
|
1289
|
+
if (code >= 55296 && code <= 57343) code = 65533;
|
|
1290
|
+
if (code < 128) bytes.push(code);
|
|
1291
|
+
else if (code < 2048) bytes.push(192 | code >> 6, 128 | code & 63);
|
|
1292
|
+
else if (code < 65536) bytes.push(224 | code >> 12, 128 | code >> 6 & 63, 128 | code & 63);
|
|
1293
|
+
else bytes.push(240 | code >> 18, 128 | code >> 12 & 63, 128 | code >> 6 & 63, 128 | code & 63);
|
|
1294
|
+
}
|
|
1295
|
+
return new Uint8Array(bytes);
|
|
1296
|
+
}
|
|
1297
|
+
function crc32(bytes) {
|
|
1298
|
+
let crc = 0xffffffff;
|
|
1299
|
+
for (const byte of bytes) {
|
|
1300
|
+
crc ^= byte;
|
|
1301
|
+
for (let i = 0; i < 8; i++) crc = crc >>> 1 ^ -(crc & 1) & 0xedb88320;
|
|
1302
|
+
}
|
|
1303
|
+
return (crc ^ 0xffffffff) >>> 0;
|
|
1304
|
+
}
|
|
1305
|
+
function createSkillZip(pack) {
|
|
1306
|
+
if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(pack.id)) throw new Error("Invalid pack id");
|
|
1307
|
+
const name = utf8(`.claude/skills/${pack.id}/SKILL.md`);
|
|
1308
|
+
const content = utf8(createSkillMarkdown(pack));
|
|
1309
|
+
if (name.length > 65535 || content.length > 0xffffffff - name.length - 76) throw new Error("Skill is too large for ZIP");
|
|
1310
|
+
const localSize = 30 + name.length + content.length;
|
|
1311
|
+
const centralSize = 46 + name.length;
|
|
1312
|
+
const zip = new Uint8Array(localSize + centralSize + 22);
|
|
1313
|
+
const view = new DataView(zip.buffer);
|
|
1314
|
+
const u16 = (offset, value) => view.setUint16(offset, value, true);
|
|
1315
|
+
const u32 = (offset, value) => view.setUint32(offset, value, true);
|
|
1316
|
+
const crc = crc32(content);
|
|
1317
|
+
u32(0, 67324752);
|
|
1318
|
+
u16(4, 20);
|
|
1319
|
+
u16(6, 2048);
|
|
1320
|
+
u16(12, 33);
|
|
1321
|
+
u32(14, crc);
|
|
1322
|
+
u32(18, content.length);
|
|
1323
|
+
u32(22, content.length);
|
|
1324
|
+
u16(26, name.length);
|
|
1325
|
+
zip.set(name, 30);
|
|
1326
|
+
zip.set(content, 30 + name.length);
|
|
1327
|
+
const c = localSize;
|
|
1328
|
+
u32(c, 33639248);
|
|
1329
|
+
u16(c + 4, 20);
|
|
1330
|
+
u16(c + 6, 20);
|
|
1331
|
+
u16(c + 8, 2048);
|
|
1332
|
+
u16(c + 14, 33);
|
|
1333
|
+
u32(c + 16, crc);
|
|
1334
|
+
u32(c + 20, content.length);
|
|
1335
|
+
u32(c + 24, content.length);
|
|
1336
|
+
u16(c + 28, name.length);
|
|
1337
|
+
zip.set(name, c + 46);
|
|
1338
|
+
const e = c + centralSize;
|
|
1339
|
+
u32(e, 0x6054b50);
|
|
1340
|
+
u16(e + 8, 1);
|
|
1341
|
+
u16(e + 10, 1);
|
|
1342
|
+
u32(e + 12, centralSize);
|
|
1343
|
+
u32(e + 16, localSize);
|
|
1344
|
+
return zip;
|
|
1345
|
+
}
|
|
1346
|
+
export { STORE_KEY, STORE_MAX_BYTES, StaticEvaluationError, buildForbiddenDictionary, buildImportFiles, buy, checkDistillation, classify, classifyParagraphs, createInitialStore, createPack, createSkillMarkdown, createSkillZip, decideBuy, distill, distilledMarkdown, earnings, evaluateKeywords, evaluateStatic, findImportConflicts, hasPurchased, hasUnconfirmedParagraphs, load, parse, parseStore, passesPruning, previewPackRedactions, purchase, recordSearch, rescan, scrub, scrubDetailed, search, serializeStore, setTxResult, validateStore };
|